Vue3中的组件通信方式

1,581 阅读6分钟

代码是vue3.2的<script setup />的编写方式,主要有以下七种组件通信方式:

1、props 父向子通信
2、emit 子向父通信
3、v-model 父向子通信
4、refs 子向父通信
5、provide/inject 父向子、兄弟之间通信
6、eventBus 父向子通信(Vue3移除) 【官方推荐使用 mitttiny-emitter,使用pubsub-js也可以】
7、vuex/pinia 父子、子父间通信

eventBus在Vue3中移除的原因,盲猜可能是出于更好的性能考虑吧,也有可能是为了更贴切我们日常的编程直觉吧。毕竟实现一个简单的 EventBus 需要生成一个复杂的 Vue 实例感觉不是太好,借助于一些专注的库来实现这个功能应该会更好。

1、Props【父向子通信】

props 是 Vue 中最常见的父子通信方式

父组件代码如下:


<template>  
    <!-- 子组件 -->  
    <child-components :list="list"></child-components>  
    <!-- 父组件 -->  
    <div class="child-wrap input-group">  
        <input  
            v-model="value"  
            type="text"  
            class="form-control"  
            placeholder="请输入"  
            />  
        <div class="input-group-append">  
            <button @click="handleAdd" class="btn btn-primary" type="button">添加</button>  
        </div>  
    </div>  
</template>  
<script setup>  
    import { ref } from 'vue'  
    import ChildComponents from './child.vue'  
    const list = ref(['JavaScript', 'HTML', 'CSS'])  
    const value = ref('')  
    // add 触发后的事件处理函数  
    const handleAdd = () => {  
        list.value.push(value.value)  
        value.value = ''  
    }  
</script>

子组件只需要渲染父组件传递的值,代码如下:

<template>  
    <ul class="parent list-group">  
        <li class="list-group-item" v-for="i in props.list" :key="i">{{ i }}</li>  
    </ul>  
</template>  
<script setup>  
    import { defineProps } from 'vue'  
    const props = defineProps({  
        list: {  
            type: Array,  
            default: () => [],  
        },  
    })  
</script>

2、Emit【子向父通信】

父组件中定义列表,子组件只需要传递添加的值

子组件代码如下:

<template>  
    <div class="child-wrap input-group">  
        <input  
            v-model="value"  
            type="text"  
            class="form-control"  
            placeholder="请输入"  
            />  
        <div class="input-group-append">  
            <button @click="handleSubmit" class="btn btn-primary" type="button">添加</button>  
        </div>  
    </div>  
</template>  
<script setup>  
    import { ref, defineEmits } from 'vue'  
    const value = ref('')  
    const emits = defineEmits(['add'])  
    const handleSubmit = () => {  
        // 向父组件派发事件,事件名字叫 add
        emits('add', value.value)  
        value.value = ''  
    }  
</script>

在子组件中点击【添加】按钮后,emit一个自定义事件,并将添加的值作为参数传递

父组件代码如下:

<template>  
    <!-- 父组件 -->  
    <ul class="parent list-group">  
    <li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>  
    </ul>  
    <!-- 子组件 -->  
    <child-components @add="handleAdd"></child-components>  
</template>  
<script setup>  
    import { ref } from 'vue'  
    import ChildComponents from './child.vue'  
    const list = ref(['JavaScript', 'HTML', 'CSS'])  
    // add 触发后的事件处理函数  
    const handleAdd = value => {  
        list.value.push(value)  
    }  
</script>

在父组件中只需要监听子组件自定义的事件,然后执行对应的添加操作

3、v-model【父向子通信】

v-model是Vue中一个比较出色的语法糖,就比如下面这段代码

<ChildComponent v-model:title="pageTitle" />

就是下面这段代码的简写形势

<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />

子组件代码:

<template>  
    <div class="child-wrap input-group">  
        <input  
            v-model="value"  
            type="text"  
            class="form-control"  
            placeholder="请输入"  
        />  
        <div class="input-group-append">  
            <button @click="handleAdd" class="btn btn-primary" type="button">添加</button>  
        </div>  
    </div>  
</template>  
<script setup>  
    import { ref, defineEmits, defineProps } from 'vue'  
    const value = ref('')  
    const props = defineProps({  
        list: {  
            type: Array,  
            default: () => [],  
        },  
    })  
    const emits = defineEmits(['update:list'])  
    // 添加操作  
    const handleAdd = () => {  
        const arr = props.list  
        arr.push(value.value)  
        emits('update:list', arr)  
        value.value = ''  
    }  
</script>

在子组件中先定义props和emits,然后添加完成之后emit指定事件

注:update:*是Vue中的固定写法,*号表示props中的某个属性名

父组件中使用就比较简单,代码如下:

<template>  
    <!-- 父组件 -->  
    <ul class="parent list-group">  
        <li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>  
    </ul>  
    <!-- 子组件 -->  
    <child-components v-model:list="list"></child-components>  
</template>  
<script setup>  
    import { ref } from 'vue'  
    import ChildComponents from './child.vue'  
    const list = ref(['JavaScript', 'HTML', 'CSS'])  
</script>

4、Refs【子向父通信】

在使用vue2的Options API时,可以通过this.$refs.name的方式获取指定元素或者组件,但是组合式API中就无法使用这种方式获取。如果想要通过ref的方式获取组件或者元素,需要定义一个同名的Ref对象,在组件挂载后就可以访问了

父组件代码如下:

<template> 
    <ul class="parent list-group">  
        <li class="list-group-item" v-for="i in childRefs?.list" :key="i">  {{ i }}  </li>  
    </ul>  
    <!-- ref的值 与 父组件 <script> 中的 某个ref 保持一致 -->  
    <child-components ref="childRefs"></child-components>  
</template>  
<script setup>  
    import { ref } from 'vue'  
    import ChildComponents from './child.vue'  
    const childRefs = ref(null) // 代表的就是获取到的子组件 
</script>

子组件代码如下:

<template>  
    <div class="child-wrap input-group">  
        <input  
            v-model="value"  
            type="text"  
            class="form-control"  
            placeholder="请输入"  
            />  
        <div class="input-group-append">  
            <button @click="handleAdd" class="btn btn-primary" type="button">添加</button>  
        </div>  
    </div>  
</template>  
<script setup>  
    import { ref, defineExpose } from 'vue'  
    const list = ref(['JavaScript', 'HTML', 'CSS'])  
    const value = ref('')  
    // add 触发后的事件处理函数  
    const handleAdd = () => {  
        list.value.push(value.value)  
        value.value = ''  
    }  
    defineExpose({ list })  
</script>

setup组件默认是关闭的(相当于单独的封装好的盒子),即通过模板ref获取到的组件的公开实例,不会暴露任何在<script setup>中声明的内容。如果需要公开,需要通过defineExposeAPI暴露出去(把盒子打开拿出某一个东西,给外部使用)

5、provide/inject【父子、兄弟通信】

provide和inject是Vue中提供的一对API,无论层级有多深,都可以通过这对API实现

父组件代码如下:

<template>  
    <!-- 子组件 -->  
    <child-components></child-components>  
    <!-- 父组件 -->  
    <div class="child-wrap input-group">  
        <input  
            v-model="value"  
            type="text"  
            class="form-control"  
            placeholder="请输入"  
            />  
        <div class="input-group-append">  
            <button @click="handleAdd" class="btn btn-primary" type="button">添加</button>  
        </div>  
    </div>  
</template>  
<script setup>  
    import { ref, provide } from 'vue'  
    import ChildComponents from './child.vue'  
    const list = ref(['JavaScript', 'HTML', 'CSS'])  
    const value = ref('')  
    // 向子组件提供数据  
    provide('list', list.value)  
    // add 触发后的事件处理函数  
    const handleAdd = () => {  
        list.value.push(value.value)  
        value.value = ''  
    }  
</script>

子组件代码如下:

<template>  
    <ul class="parent list-group">  
        <li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>  
    </ul>  
</template>  
<script setup>  
    import { inject } from 'vue'  
    // 接受父组件提供的数据  
    const list = inject('list')  
</script>

值得注意的是使用provide进行数据传递时,尽量用readonly进行数据的包装,避免子组件修改父级传递过去的数据

6、eventBus【父子间通信】

Vue3 中移除了 eventBus,但可以借助第三方工具来完成。Vue 官方推荐使用 mitt 或 tiny-emitter,使用pubsub-js也可以

业务上通信困难的时候就会用,通常作为事件总线使用

作为事件总线只实现了通信层,那就有以下的问题:

1. 命名问题。事件通信并不存在命名空间

2. 生命周期。事件通信的生命周期依赖于组件的加载与卸载,需要在组件卸载的时候,移除掉它。否则会有内存泄漏的隐患

3. 难以追踪数据变化

在大多数情况下,不建议使用全局事件总线来实现组件通信。虽然比较简单粗暴,但是维护事件总线从长远来看是个大问题

Vue3 中之所以移除了事件总线,是因为在使用该功能时,很容易导致代码的混乱,不同的组件抛出各种事件,这些事件又被各种组件接收,太多时就会产生难以溯源的情况,不知道这些事件都是从哪个组件发出来的,让代码变得难以维护。并且有些开发者在使用时,不遵守规范,只使用$on,不使用$off关闭,浪费性能。

7、vuex/pinia【父子、子父间通信】

Vuex 和 Pinia 是 Vue3 中的状态管理工具,使用这两个工具可以轻松实现组件通信,有关详细信息,参阅官方文档即可

7-1、方式一 安装插件一:npm i pinia-plugin-persistedstate

点击查看插件的官网: prazdevs.github.io/pinia-plugi…

常见疑问

  • 模块做了持久化后,以后数据会不会变,怎么办?

    • 先读取本地的数据,如果新的请求获取到新数据,会自动把新数据覆盖掉旧的数据。
    • 无需额外处理,插件会自己更新到最新数据。

相关的文章:jiuaidu.com/jianzhan/91…

7-2、方式二 安装插件二:pinia-plugin-persist

1、其中Pinia可以实现数据持久化存储,需要安装插件:pinia-plugin-persist

npm i pinia-plugin-persist --save

2、store/index.ts中引入并挂载

import { createPinia, defineStore } from "pinia";
import piniaPluginPersist from 'pinia-plugin-persist'
 
const store = createPinia()
store.use(piniaPluginPersist)
 
export default store

3、使用方法

enabled: true即表示开启数据缓存

export const useUserStore = defineStore({id: 'userId',
  state: () => {
    return {
      userInfo:{
        name:'Ghmin',
        age:18,
        sex:'男'
        },
      id:'666666'
    }
  },
  // 开启数据缓存
  persist: {
    enabled: true
  }
})

这个时候数据默认是存在 sessionStorage 里,需要修改的话如下:

// 开启数据缓存
persist: {
  enabled: true,
  strategies: [
    {
      key: 'userInfo',//设置存储的key
      storage: localStorage,//表示存储在localStorage
    }
  ]
}

默认所有 state 都会进行缓存,如果你不想所有的数据都持久化存储,那么可以通过 paths 指定要长久化的字段,其余的字段则不会进行长久化,如下:

// 开启数据缓存
persist: {
  enabled: true,
  strategies: [
    {
      key: 'userInfo',//设置存储的key
      storage: localStorage,//表示存储在localStorage
      paths: ['id'],//指定要长久化的字段
    }
  ]
}