Vue 组件通信方式

Vue 提供了多种组件通信方式,适用于不同场景的需求。以下是主要的通信方式:

1. 父子组件通信

1.1 Props 向下传递

// 父组件
<ChildComponent :message="parentMessage" />

// 子组件
props: {
  message: String
}

1.2 自定义事件向上传递

// 子组件
this.$emit('event-name', data)

// 父组件
<ChildComponent @event-name="handleEvent" />

1.3 v-model 双向绑定

// 父组件
<ChildComponent v-model="value" />

// 子组件
props: ['value'],
methods: {
  updateValue(newValue) {
    this.$emit('input', newValue)
  }
}

1.4 .sync 修饰符 (Vue 2.x)

// 父组件
<ChildComponent :title.sync="doc.title" />

// 子组件
this.$emit('update:title', newTitle)

 1.5 parent 和parent和children (不推荐)

// 访问父组件
this.$parent.someMethod()

// 访问子组件
this.$children[0].someMethod()

1.6 Refs (获取子组件实例)

// 父组件
<ChildComponent ref="child" />

// 访问子组件
this.$refs.child.someMethod()

1.7 作用域插槽 

// 子组件
<slot :user="user"></slot>

// 父组件
<ChildComponent>
  <template v-slot:default="slotProps">
    {{ slotProps.user.name }}
  </template>
</ChildComponent>

2. 祖 孙/后代组件通信

Provide/Inject

// 祖先组件
provide() {
  return {
    theme: this.theme
  }
}

// 后代组件
inject: ['theme']

3. 全局事件总线(兄弟组件、无关联组件)

// 创建事件总线 (通常在 main.js)
Vue.prototype.$bus = new Vue()

// 组件A 发送事件
this.$bus.$emit('event-name', data)

// 组件B 接收事件
this.$bus.$on('event-name', (data) => {
  // 处理数据
})

// 记得在组件销毁前移除监听
beforeDestroy() {
  this.$bus.$off('event-name')
}

4. Vuex 状态管理(适用于大型应用中的全局状态管理)

// 存储状态
this.$store.commit('mutationName', payload)

// 获取状态
this.$store.state.moduleName.stateName

// 异步操作
this.$store.dispatch('actionName', payload)

5. attrs 和attrs和listeners (Vue 2.x)

// 父组件
<ChildComponent v-bind="$attrs" v-on="$listeners" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大樊子

有钱捧个人场,没钱捧个钱场😜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值