vue2中祖父组件和孙组件事件通信

本文介绍了三种在Vue中实现组件间通信的方式,包括通过$parent属性层层传递并使用emit触发事件,使用provide和inject进行祖先组件的方法或属性注入,以及利用事件总线(Vue实例)进行跨级通信。

1、使用parent属性访问祖父组件,并通过parent属性访问祖父组件,并通过parent属性访问祖父组件,并通过emit方法触发祖父组件的事件

this.$parent.$emit('event-name', data);

2、使用provide和inject方法,在祖父组件中提供一个方法或属性,孙组件中通过inject方法获取这个方法或属性,并在孙组件中调用该方法或属性来触发祖父组件

// 祖父组件中
provide() {
  return {
    trigger: this.trigger
  }
},
methods: {
  trigger(data) {
    // 处理数据
  }
}

// 孙组件中
inject: ['trigger'],
methods: {
  handleClick() {
    this.trigger(data);
  }
}

3、使用事件总线,祖父组件中创建一个Vue实例作为事件总线,然后在祖父组件、父组件和孙组件中分别使用emit和emit和emiton方法来进行事件的传递和监听。

// 祖父组件中
const eventBus = new Vue();

// 父组件中
eventBus.$on('event-name', data => {
  // 处理数据
})
// 孙组件中
eventBus.$emit('event-name', data);
### Vue2组件之间通信的方法 在 Vue2 中,爷组件间的通信可以通过 `$attrs` `$listeners` 实现。这种方式允许祖代组件传递数据给后代组件,而不需要通过中间的父级组件。 #### 使用 $attrs $listeners 进行通信 当使用 `$attrs` 时,可以将属性从祖父组件传递到组件,跳过父组件。同样地,使用 `$listeners` 可以让事件监听器也能够这样传递下去[^1]。 下面是一个具体的例子来展示如何利用这些功能: #### 示例代码 ##### Grandpa.vue (祖父组件) ```html <template> <div class="grandpa"> <h3>Grandpa Component</h3> <!-- 将 message message2 属性以及 sendGrandpaMessage 方法传入 Child --> <child v-bind="$attrs" v-on="$listeners"></child> </div> </template> <script> import Child from './Child.vue'; export default { name: 'Grandpa', components: { Child }, props: ['message', 'message2'], methods: { sendGrandpaMessage() { alert(this.message); } } }; </script> ``` 在这个例子中,`v-bind="$attrs"` 表示所有的未声明 prop 都会被绑定到子组件上;`v-on="$listeners"` 则表示所有自定义事件都会被转发给子组件。 ##### Child.vue (父组件) ```html <template> <div class="child"> <h4>Child Component</h4> <!-- 不做任何处理直接透传 attrs listeners 至 grand-child --> <grand-child v-bind="$attrs" v-on="$listeners"></grand-child> </div> </template> <script> import GrandChild from './GrandChild.vue'; export default { name: 'Child', components: { GrandChild }, inheritAttrs: false // 关闭自动继承 attributes 的行为,默认为 true }; </script> ``` 这里设置了 `inheritAttrs: false` 是为了防止不必要的默认行为影响布局或其他样式设置。 ##### GrandChild.vue (组件) ```html <template> <div class="grand-child"> <p>{{ message }}</p> <button @click="sendGrandpaMessage">Send Message to Grandpa</button> </div> </template> <script> export default { name: 'GrandChild', props: ['message'], // 接收来自 grandfather 的 message 参数 methods: { ...mapListeners(['sendGrandpaMessage']) // 映射并接收来自 grandfather 的方法调用 } }; </script> ``` 此部分展示了如何在一个多层嵌套结构里有效地管理状态流动交互逻辑,使得即使不是直接相连的组件也能方便地共享信息响应动作。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值