Vue 常见的几种通信方式(总结)

前言

Vue的通信方式,相信各位小伙伴都已经滚瓜烂收了,但是我估计咱们平常用到的就那么几个,那么剩余的哪些具体是怎么使用的,或者再去温习一下,我觉得也是很有必要的。

1.props/emit

父组件

html 复制代码
<template>
  <h2>props传递和emit传递</h2>
  <CustomPropsEmits :title="pageTitle" @update-title="handleTitleUpdate"></CustomPropsEmits>
</template>

<script setup>
import { ref} from 'vue'
import CustomPropsEmits from './components/customPropsEmits.vue'

// 父组件的状态
const pageTitle = ref('父组件的值')

// 父组件处理子组件的事件
const handleTitleUpdate = (newTitle) => {
  pageTitle.value = newTitle
}

</script>

子组件

html 复制代码
<template>
  <div>
    <h3>{{ props.title }}</h3>
    <el-button @click="updateTitle">Update 父组件</el-button>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'
// 使用 defineProps 接收父组件传递的 prop
const props = defineProps({
  title: {
    type: String,
    required: true
  }
})

// 定义 emit 用于发射事件
const emit = defineEmits(['update-title'])

// 点击按钮时发射事件
const updateTitle = () => {
  emit('update-title', '子组件去改变')
}
</script>

2.v-model

父组件

html 复制代码
<template> 
 <h2>v-model传值</h2>
  <p>{{ message }}</p>
  <CustomVodel v-model="message"></CustomVodel>
</template>

<script setup>
import {ref} from 'vue'
import CustomVodel from './components/customVodel.vue'


const message = ref('Hello, World!')
</script>

子组件

html 复制代码
<template>
  <div>
    <input v-model="localValue" />
  </div>
</template>

<script setup>
import { defineProps, ref, watch } from 'vue'
// 使用 defineProps 接收父组件传递的 prop
const props = defineProps({
  modelValue: {
    type: String,
    required: true
  }
})

// 定义 emit 用于发射事件
const emit = defineEmits(['update:modelValue'])

// 创建一个局部变量,保存 modelValue 的值
const localValue = ref(props.modelValue)

// 监听 localValue 的变化,并发射事件通知父组件
watch(localValue, (newValue) => {
  emit('update:modelValue', newValue)
})
</script>

3.refs

父组件

html 复制代码
<template>  
<h2>refs 子向父通信</h2>
  <el-button @click="callChildMethod">Call Child Method</el-button>
  <CustomRef ref="childRef"></CustomRef>s
</template> 

<script setup>
import { ref, provide } from 'vue'-
import CustomRef from './components/customRef.vue'
const childRef = ref(null)
// 调用子组件的方法
const callChildMethod = () => {
  if (childRef.value) {
    childRef.value.sayHello() // 调用子组件的方法
  }
}

子组件一定要搭配defineExpose使用

html 复制代码
<template>
  <div>
    <p>Hello, I'm the Child Component!</p>
  </div>
</template>

<script setup>
import { defineExpose } from 'vue'

// 定义子组件的方法
// eslint-disable-next-line no-unused-vars
const sayHello = () => {
  console.log('Hello from Child Component!')
}
defineExpose({ sayHello })
</script>

4.provide/inject

父组件

javascript 复制代码
import { ref, provide } from 'vue'

provide('sharedData', 'This is provided data')

子组件

html 复制代码
<template>
  <div>{{ injectedData }}</div>
  <p>这里是传递下来的组件</p>
</template>

<script setup>
import { inject } from 'vue'

const injectedData = inject('sharedData')
</script>

5.eventBus

父向子通信(Vue3移除) 【官方推荐使用 mitt 或 tiny-emitter,使用pubsub-js也可以】

6.状态管理器Vuex/Pinia

注意要配合一个插件才可以实现持久化存储

"pinia-plugin-persistedstate"

这里的代码我只写仓库里的代码

javascript 复制代码
// 此商店用于存放全局的一些状态
import { defineStore } from 'pinia'

export const useAllStore = defineStore('all', {
  state: () => ({
    isCollapse: false,
    defaultActive: '1-1'
  }),
  actions: {
    SetIsCollapseInfo(data) {
      this.isCollapse = data
    },
    setDefaultActive(data) {
      this.defaultActive = data.toString()
    }
  },
  persist: {
    paths: ['isCollapse', 'defaultActive'] //只有 isCollapse,defaultActive被持久化保存
  }
})

7.本地存储也可以

基本也就这些,如果有好的方法欢迎评论区来讨论。

相关推荐
梵得儿SHI13 分钟前
Vue 核心语法之组件基础与通信:从创建到注册的完整指南
前端·javascript·vue.js·组件化开发·全局注册·vue组件的本质·局部注册和异步组件
MQliferecord27 分钟前
如何快速实现响应式多屏幕适配
前端
欧阳的棉花糖28 分钟前
不用记复杂路径!3 步让你的 JS 脚本像 “vue create” 一样好用
javascript
韭菜炒大葱29 分钟前
从回调到async/await:JavaScript异步编程的进化之路
前端·javascript·面试
凌晨起床31 分钟前
前端开发规范
前端
与妖为邻37 分钟前
HTML5动态时间显示组件
javascript·css·css3
烤汉堡41 分钟前
Python入门到实战:post请求和响应
python·html
Cache技术分享41 分钟前
247. Java 集合 - 为什么要远离 Stack 类?
前端·后端
●VON43 分钟前
Electron for HarmonyOS 开发环境搭建
javascript·electron·harmonyos
v***91301 小时前
Spring+Quartz实现定时任务的配置方法
android·前端·后端