Vue 组件通信
1.父组件向子组件传递信息
// parent.vue child是子组件 需要传递的信息是msg
<child :msg="message"></child>
// child.vue 子组件通过props数据来接收信息
data() {
return {
props:['msg']
}
}
2.子组件向父组件传递信息
// child.vue
this.$emit('msg', 'message')
// parent.vue
<child @msg="msg"></child>
3.provide/inject组合
provide/inject 组合以允许一个祖先组件向其所有子孙后代注入一个依赖,可以注入属性和方法,从而实现跨级父子组件通信。在开发高阶组件和组件库的时候尤其好用。
// 父组件 index.vue
data() {
return {
title: 'bubuzou.com',
}
}
provide() {
return {
detail: {
title: this.title,
change: (val) => {
console.log( val )
}
}
}
}
// 子孙组件 children.vue
inject: ['detail'],
mounted() {
console.log(this.detail.title) // bubuzou.com
this.detail.title = 'hello world' // 虽然值被改变了,但是父组件中 title 并不会重新渲染
this.detail.change('改变后的值') // 执行这句后将打印:改变后的值
}
4.EventBus 进行信息的发布和订阅,实现在任意2个组件之间通信
两种写法都可以初始化一个 eventBus 对象
// 1.通过导出一个 Vue 实例,然后在需要的地方引入:
// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
使用 EventBus 订阅和发布消息:
import {EventBus} from '../utils/eventBus.js'
// 订阅处
EventBus.$on('update', val => {})
// 发布处
EventBus.$emit('update', '更新信息')
//2.在 main.js 中初始化一个全局的事件总线:
// main.js
Vue.prototype.$eventBus = new Vue()
// 订阅处
this.$eventBus.$on('update', val => {})
// 发布处
this.$eventBus.$emit('update', '更新信息')
5.attrs/listeners 可以进行跨级的组件通信
$attrs 包含了父级作用域中不作为 prop 的属性绑定(class 和 style 除外)
// 父组件 index.vue
<list class="list-class" title="标题" desc="描述" :list="list"></list>
// 子组件 list.vue
props: {
list: [],
},
mounted() {
console.log(this.$attrs) // {title: "标题", desc: "描述"}
}
------------------------------------------------------------------------
// 子组件 list.vue
<detail v-bind="$attrs"></detial>
// 孙组件 detail.vue
mounted() {
console.log(this.$attrs) // {title: "标题", desc: "描述"}
}
在子组件中我们定义了一个 v-bind="$attrs" 可以把父级传过来的参数,去除 props、class 和 style 之后剩下的继续往下级传递,这样就实现了跨级的组件通信。
attrs 是可以进行跨级的参数传递,实现父到子的通信;同样的,通过 listeners 用类似的操作方式可以进行跨级的事件传递,实现子到父的通信。listeners 包含了父作用域中不含 .native 修饰的 v-on 事件监听器,通过 v-on="$listeners" 传递到子组件内部。
// 父组件 index.vue
<list @change="change" @update.native="update"></list>
// 子组件 list.vue
<detail v-on="$listeners"></detail>
// 孙组件 detail.vue
mounted() {
this.$listeners.change()
this.$listeners.update() // TypeError: this.$listeners.update is not a function
}
2751

被折叠的 条评论
为什么被折叠?



