跳到主要内容

组件间通信

组件间通信

1.vue2 的组件间通信方式

组件通信的方式如下:

(1) props / $emit

父组件通过props向子组件传递数据,子组件通过$emit和父组件通信

1. 父组件向子组件传值
  • props只能是父组件向子组件进行传值,props使得父子组件之间形成了一个单向下行绑定。子组件的数据会随着父组件不断更新。
  • props 可以显示定义一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以传递一个函数。
  • props属性名规则:若在props中使用驼峰形式,模板中需要使用短横线的形式
// 父组件
<template>
<div id="father">
<son :msg="msgData" :fn="myFunction"></son>
</div>
</template>

<script>
import son from "./son.vue";
export default {
name: father,
data() {
msgData: "父组件数据";
},
methods: {
myFunction() {
console.log("vue");
}
},
components: {
son
}
};
</script>

// 子组件
<template>
<div id="son">
<p>{{msg}}</p>
<button @click="fn">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
props: ["msg", "fn"]
};
</script>
2. 子组件向父组件传值
  • $emit绑定一个自定义事件,当这个事件被执行的时就会将参数传递给父组件,而父组件通过v-on监听并接收参数。
// 父组件
<template>
<div class="section">
<com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
<p>{{currentIndex}}</p>
</div>
</template>

<script>
import comArticle from './test/article.vue'
export default {
name: 'comArticle',
components: { comArticle },
data() {
return {
currentIndex: -1,
articleList: ['红楼梦', '西游记', '三国演义']
}
},
methods: {
onEmitIndex(idx) {
this.currentIndex = idx
}
}
}
</script>


//子组件
<template>
<div>
<div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
</div>
</template>

<script>
export default {
props: ['articles'],
methods: {
emitIndex(index) {
this.$emit('onEmitIndex', index) // 触发父组件的方法,并传递参数index
}
}
}
</script>

(2)eventBus 事件总线($emit / $on

eventBus事件总线适用于父子组件非父子组件等之间的通信,使用步骤如下: (1)创建事件中心管理组件之间的通信

// event-bus.js

import Vue from "vue";
export const EventBus = new Vue();

(2)发送事件 假设有两个兄弟组件firstComsecondCom

<template>
<div>
<first-com></first-com>
<second-com></second-com>
</div>
</template>

<script>
import firstCom from './firstCom.vue'
import secondCom from './secondCom.vue'
export default {
components: { firstCom, secondCom }
}
</script>

firstCom组件中发送事件:

<template>
<div>
<button @click="add">加法</button>
</div>
</template>

<script>
import {EventBus} from './event-bus.js' // 引入事件中心

export default {
data(){
return{
num:0
}
},
methods:{
add(){
EventBus.$emit('addition', {
num:this.num++
})
}
}
}
</script>

(3)接收事件secondCom组件中发送事件:

<template>
<div>求和: {{count}}</div>
</template>

<script>
import { EventBus } from './event-bus.js'
export default {
data() {
return {
count: 0
}
},
mounted() {
EventBus.$on('addition', param => {
this.count = this.count + param.num;
})
}
}
</script>

在上述代码中,这就相当于将num值存贮在了事件总线中,在其他组件中可以直接访问。事件总线就相当于一个桥梁,不用组件通过它来通信。

虽然看起来比较简单,但是这种方法也有不变之处,如果项目过大,使用这种方式进行通信,后期维护起来会很困难。

(3)依赖注入(provide / inject)

这种方式就是 Vue 中的依赖注入,该方法用于父子组件之间的通信。当然这里所说的父子不一定是真正的父子,也可以是祖孙组件,在层数很深的情况下,可以使用这种方法来进行传值。就不用一层一层的传递了。

provide / inject是 Vue 提供的两个钩子,和datamethods是同级的。并且provide的书写形式和data一样。

  • provide 钩子用来发送数据或方法
  • inject钩子用来接收数据或方法

在父组件中:

provide() {
return {
num: this.num
};
}

在子组件中:

inject: ["num"];

还可以这样写,这样写就可以访问父组件中的所有属性:

provide() {
return {
app: this
};
}
data() {
return {
num: 1
};
}

inject: ['app']
console.log(this.app.num)

注意: 依赖注入所提供的属性是非响应式的。

(3)ref / $refs

这种方式也是实现父子组件之间的通信。

ref: 这个属性用在子组件上,它的引用就指向了子组件的实例。可以通过实例来访问组件的数据和方法。

在子组件中:

export default {
data() {
return {
name: "JavaScript",
};
},
methods: {
sayHello() {
console.log("hello");
},
},
};

在父组件中:

<template>
<child ref="child"></component-a>
</template>
<script>
import child from './child.vue'
export default {
components: { child },
mounted () {
console.log(this.$refs.child.name); // JavaScript
this.$refs.child.sayHello(); // hello
}
}
</script>

(4)$parent / $children

  • 使用$parent可以让组件访问父组件的实例(访问的是上一级父组件的属性和方法)
  • 使用$children可以让组件访问子组件的实例,但是,$children并不能保证顺序,并且访问的数据也不是响应式的。

在子组件中:

<template>
<div>
<span>{{message}}</span>
<p>获取父组件的值为: {{parentVal}}</p>
</div>
</template>

<script>
export default {
data() {
return {
message: 'Vue'
}
},
computed:{
parentVal(){
return this.$parent.msg;
}
}
}
</script>

在父组件中:

// 父组件中
<template>
<div class="hello_world">
<div>{{msg}}</div>
<child></child>
<button @click="change">点击改变子组件值</button>
</div>
</template>

<script>
import child from './child.vue'
export default {
components: { child },
data() {
return {
msg: 'Welcome'
}
},
methods: {
change() {
// 获取到子组件
this.$children[0].message = 'JavaScript'
}
}
}
</script>

在上面的代码中,子组件获取到了父组件的parentVal值,父组件改变了子组件中message的值。 需要注意:

  • 通过$parent访问到的是上一级父组件的实例,可以使用$root来访问根组件的实例
  • 在组件中使用$children拿到的是所有的子组件的实例,它是一个数组,并且是无序的
  • 在根组件#app上拿$parent得到的是new Vue()的实例,在这实例上再拿$parent得到的是undefined,而在最底层的子组件拿$children是个空数组
  • $children 的值是数组,而$parent是个对象

(5)$attrs / $listeners

考虑一种场景,如果 A 是 B 组件的父组件,B 是 C 组件的父组件。如果想要组件 A 给组件 C 传递数据,这种隔代的数据,该使用哪种方式呢?

如果是用props/$emit来一级一级的传递,确实可以完成,但是比较复杂;如果使用事件总线,在多人开发或者项目较大的时候,维护起来很麻烦;如果使用 Vuex,的确也可以,但是如果仅仅是传递数据,那可能就有点浪费了。

针对上述情况,Vue 引入了$attrs / $listeners,实现组件之间的跨代通信。

先来看一下inheritAttrs,它的默认值 true,继承所有的父组件属性除props之外的所有属性;inheritAttrs:false 只继承 class 属性 。

  • $attrs:继承所有的父组件属性(除了 prop 传递的属性、class 和 style ),一般用在子组件的子元素上
  • $listeners:该属性是一个对象,里面包含了作用在这个组件上的所有监听器,可以配合 v-on="$listeners" 将所有的事件监听器指向这个组件的某个特定的子元素。(相当于子组件继承父组件的事件)

A 组件(APP.vue):

<template>
<div id="app">
//此处监听了两个事件,可以在B组件或者C组件中直接触发
<child1 :p-child1="child1" :p-child2="child2" @test1="onTest1" @test2="onTest2"></child1>
</div>
</template>
<script>
import Child1 from './Child1.vue';
export default {
components: { Child1 },
methods: {
onTest1() {
console.log('test1 running');
},
onTest2() {
console.log('test2 running');
}
}
};
</script>

B 组件(Child1.vue):

<template>
<div class="child-1">
<p>props: {{pChild1}}</p>
<p>$attrs: {{$attrs}}</p>
<child2 v-bind="$attrs" v-on="$listeners"></child2>
</div>
</template>
<script>
import Child2 from './Child2.vue';
export default {
props: ['pChild1'],
components: { Child2 },
inheritAttrs: false,
mounted() {
this.$emit('test1'); // 触发APP.vue中的test1方法
}
};
</script>

C 组件 (Child2.vue):

<template>
<div class="child-2">
<p>props: {{pChild2}}</p>
<p>$attrs: {{$attrs}}</p>
</div>
</template>
<script>
export default {
props: ['pChild2'],
inheritAttrs: false,
mounted() {
this.$emit('test2');// 触发APP.vue中的test2方法
}
};
</script>

在上述代码中:

  • C 组件中能直接触发 test 的原因在于 B 组件调用 C 组件时 使用 v-on 绑定了$listeners 属性
  • 在 B 组件中通过 v-bind 绑定$attrs属性,C 组件可以直接获取到 A 组件中传递下来的 props(除了 B 组件中 props 声明的)

(6)总结

(1)父子组件间通信

  • 子组件通过 props 属性来接受父组件的数据,然后父组件在子组件上注册监听事件,子组件通过 emit 触发事件来向父组件发送数据。
  • 通过 ref 属性给子组件设置一个名字。父组件通过 $refs 组件名来获得子组件,子组件通过 $parent 获得父组件,这样也可以实现通信。
  • 使用 provide/inject,在父组件中通过 provide 提供变量,在子组件中通过 inject 来将变量注入到组件中。不论子组件有多深,只要调用了 inject 那么就可以注入 provide 中的数据。

(2)兄弟组件间通信

  • 使用 eventBus 的方法,它的本质是通过创建一个空的 Vue 实例来作为消息传递的对象,通信的组件引入这个实例,通信的组件通过在这个实例上监听和触发事件,来实现消息的传递。
  • 通过 $parent/$refs 来获取到兄弟组件,也可以进行通信。

(3)任意组件之间

  • 使用 eventBus ,其实就是创建一个事件中心,相当于中转站,可以用它来传递事件和接收事件。

如果业务逻辑复杂,很多组件之间需要同时处理一些公共的数据,这个时候采用上面这一些方法可能不利于项目的维护。这个时候可以使用 vuex ,vuex 的思想就是将这一些公共的数据抽离出来,将它作为一个全局的变量来管理,然后其他组件就可以对这个公共数据进行读写操作,这样达到了解耦的目的。

2.vue3 的组件间通信方式

七种组件通信方式:

  • props
  • emit
  • v-model
  • refs
  • provide/inject
  • eventBus
  • vuex/pinia(状态管理工具)

Props 方式

Props方式是 Vue 中最常见的一种父传子的一种方式,使用也比较简单。

根据上面的 demo,我们将数据以及对数据的操作定义在父组件,子组件仅做列表的一个渲染;

父组件代码如下:

<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>

emit 方式

emit方式也是 Vue 中最常见的组件通信方式,该方式用于子传父

根据上面的 demo,我们将列表定义在父组件,子组件只需要传递添加的值即可。

子组件代码如下:

<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 = () => {
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>

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

v-model 方式

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

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

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

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

v-model确实简便了不少,现在我们就来看一下上面那个 demo,如何用 v-model 实现。

子组件

<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>

在子组件中我们首先定义propsemits,然后添加完成之后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>

refs 方式

在使用选项式 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>中的保持一致 -->
<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>**中声明的绑定**。如果需要公开需要通过**defineExpose** API 暴露**

provide/inject 方式

provideinject是 Vue 中提供的一对 API,该 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进行数据的包装,避免子组件修改父级传递过去的数据

事件总线

Vue3 中移除了事件总线,但是可以借助于第三方工具来完成,Vue 官方推荐mitttiny-emitter

在大多数情况下不推荐使用全局事件总线的方式来实现组件通信,虽然比较简单粗暴,但是长久来说维护事件总线是一个大难题,所以这里就不展开讲解了,具体可以阅读具体工具的文档