vue实现反向推送
Vue 实现反向推送的方法
反向推送通常指子组件向父组件传递数据或触发事件。Vue 提供了多种方式实现这一功能:
使用 $emit 触发自定义事件
子组件通过 $emit 触发事件,父组件通过 v-on 监听:
// 子组件
this.$emit('custom-event', dataToSend)
// 父组件模板
<child-component @custom-event="handleEvent"></child-component>
使用 v-model 实现双向绑定
适用于表单类组件的双向数据绑定:

// 子组件
props: ['value'],
methods: {
updateValue(newVal) {
this.$emit('input', newVal)
}
}
// 父组件
<child-component v-model="parentData"></child-component>
使用 .sync 修饰符
Vue 2.3+ 提供的语法糖,实现特定 prop 的双向绑定:
// 子组件
this.$emit('update:title', newTitle)
// 父组件
<child-component :title.sync="parentTitle"></child-component>
使用 Provide/Inject
跨层级组件通信方案:

// 祖先组件
provide() {
return {
updateData: this.handleDataUpdate
}
}
// 后代组件
inject: ['updateData'],
methods: {
sendData() {
this.updateData(receivedData)
}
}
使用 Event Bus
创建全局事件总线实现任意组件间通信:
// 创建 Event Bus
export const EventBus = new Vue()
// 发送方组件
EventBus.$emit('event-name', payload)
// 接收方组件
EventBus.$on('event-name', payload => {
// 处理数据
})
使用 Vuex 状态管理
适合中大型应用的集中式状态管理:
// 组件中提交 mutation
this.$store.commit('mutationName', payload)
// 或分发 action
this.$store.dispatch('actionName', payload)
选择方法时应考虑组件关系复杂度,简单父子通信推荐 $emit,跨层级通信建议使用 Provide/Inject 或 Vuex,全局事件可使用 Event Bus。






