Vue 组件通信

本文深入讲解了组件通信的重要性及其实现方式,包括父子组件通信、非父子组件通信等,通过具体示例阐述了如何利用props、自定义事件、ref链和事件总线等手段进行组件间的数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 为什么要进行组件通信?

组件可以说是一个具有独立功能的整体,但是当我们要将这些组件拼接在一起时,这些组件相互之间要建立联系,这个联系我们就称之为通信

  1. 组件通信的方式有以下几种
    1. 父子组件通信
      使用props来实现

      流程:

      1. 在父组件的模板中将数据用单项数据绑定的形式,绑定在子组件身上

      2. 在子组件的配置项中可以使用一个props配置项来接收这个数据,接收时,props的取值可以使一个数组

      3. 在子组件模板中,接收到的属性可以像全局变量一样直接使用

<div id="app">
<father></father>
</div>
<template id="father">
<div>
<h3>这里是父组件</h3>
<hr>
<Son :money="money" :mask-flag="maskFlag"/>
<!-- 组件嵌套也可以使用单标签 -->
</div>
</template>
<template id="son">
<div>
<h3>这里是子组件</h3>
<p>父亲给了我 {{money}} 元钱</p>
<p> {{ maskFlag }} </p>
<!-- 这里的money就可以作为全局变量使用 -->
</div>
</template>
Vue.component('Father', {
template: '#father',
data() {
return {
money: 1000,
maskFlag:500
}
}
})
Vue.component('Son', {
template: '#son',
props: ['money'] // 子组件通过props接收数据
})
new Vue({


}).$mount('#app') // app实例的手动挂载

涉及到的问题:

问题1: props接收的money 和 子组件上绑定的自定义属性money是不是同一个?
            个人: 一般都是 自定义属性会和数据写成一致

问题2: 自定义属性的书写
              money ----> money
              mask-flag ----> maskFlag

问题3: 为什么data要定义为一个函数?
            1. 组件是一个独立的个体,那么它应该拥有自己的数据,这个数据应该是一个独立的数据
            2. 也就是说这个数据应该有独立作用域,也就是有一个独立的使用范围,这个范围就是这个组件内
            3. js的最大特征是:函数式编程 , 而函数恰好提供了独立作用域

问题4: 为什么data要有返回值?返回值还是一个对象?
            1. 因为Vue是通过observer来观察data选项的,所有必须要有返回值
            2. 因为Vue要通过es5的Object.defineProperty属性对对象进行getter和setter设置

注意:组件的根元素必须有且仅有一个

  1. 子父组件通信
流程:
                1. 在父组件的模板中,通过事件绑定的形式,绑定一个自定义事件在子组件身上
                <Son @aa = "fn"/> //这边要注意: fn是要在父组件配置项methods中定义
                2. 在子组件的配置项methods中写一个事件处理程序,在事件处理程序中触发父组件绑定的自定义事件
                Vue.component('Son',{
                    template: '#son',
                    data () {
                        return {
                            hongbao: 500
                        }
                     },
                    methods: {
                        giveFather () {
                        //如何进行父组件给子组件的自定义事件触发
                        this.$emit('give',this.hongbao)
                        }
                     }
                })
            3. 将子组件定义的事件处理程序 giveFather,绑定在子组件的按钮身上
                <template id="son">
                    <div>
                        <button @click = "giveFather"> give </button>
                        <h3> 这里是son组件 </h3>
                    </div>
                </template>
<div id="app">
<Father></Father>
</div>
<template id="father">
<div>
<h3> 这里father组件 </h3>
<p> 儿子给了我 {{ money }} </p>
<Son @give = "getHongbao"/>
</div>
</template>
<template id="son">
<div>
<button @click = "giveFather"> give </button>
<h3> 这里是son组件 </h3>
</div>
</template>
Vue.component('Father',{
template: '#father',
data () {
return {
money: 0
}
},
methods: {
getHongbao ( val ) {
console.log( 1 )
this.money = val
}
}
})


Vue.component('Son',{
template: '#son',
data () {
return {
hongbao: 500
}
},
methods: {
giveFather () {
//如何进行父组件给子组件的自定义事件触发
this.$emit('give',this.hongbao)
}
}
})


new Vue({
el: '#app'
})
  1. 非父子组件通信
    ref链
    通过ref绑定组件后,我们发现在他们的共同父组件的 $refs里面可以找到子组件
<div id="app">
<Father></Father>
</div>
<template id="father">
<!-- 组件中根元素必须唯一 -->
<div>
<h3> 这里是father </h3>
<button @click = "look"> 点击查看father的this </button>
<p> father的 n: {{ n }} </p>
<hr>
<Son ref = "son"></Son>
<Girl ref = "girl" :n = "n"></Girl>
</div>
</template>


<template id="son">
<div>
<h3> 这里是 son 1 </h3>
</div>
</template>


<template id="girl">
<div>
<h3> 这里是girl </h3>
<button @click = "out"> 输出girl的this </button>
</div>
</template>
Vue.component('Father',{
template: '#father',
data () {
return {
n: 0
}
},
methods: {
look () {
this.n = this.$refs.son.money
}
}
})


Vue.component('Son',{
template: '#son',
data () {
return {
money: 1000
}
}
})


Vue.component('Girl',{
template: '#girl',
data () {
return {
num: 0
}
},
methods: {
out () {
console.log( this )
console.log( this.$attrs )
}
}
})


new Vue({
el: '#app'
})

bus事件总线

    通过 $on来定义事件, 通过 $emit来触发事件

    案例: 哥哥揍弟弟,弟弟哭

    流程:
    1. 在其中一个组件的 挂载钩子函数 上 做事件的声明
                Vue.component('Sma',{
                    template: '#small',
                    data () {
                            return {
                                flag: false
                            }
                    },
                    mounted () { //当前组件挂载结束,也就是我们可以在页面当中看到真实dom
                   // mounted这个钩子函数的触发条件是组件创建时会自动触发
                  // 事件的声明
                  var _this = this
                  bus.$on( 'aa',function () {
                  _this.flag = true
                  console.log( this )//这里是this指的是bus, 但是我们需要的this应该是Sma这个组件
                       })
                    }
                })

        2. 在另一个组件中 通过 bus.$emit('aa')来触发这个自定义事件
<div id="app">
<Bro></Bro>
<Sma></Sma>
</div>
<template id="big">
<div>
<h3> 这里是哥哥组件 </h3>
<button @click = "hick"> 揍 </button>
</div>
</template>


<template id="small">
<div>
<h3> 这里是弟弟组件 </h3>
<p v-show = "flag"> 呜呜呜呜呜呜呜呜呜uwuwuwuwu </p>
</div>
</template>
var bus = new Vue() // bus原型上是不是有 $on $emit


Vue.component('Bro', {
template: '#big',
methods: {
hick() {
bus.$emit('aa')
}
}
})



Vue.component('Sma', {
template: '#small',
data() {
return {
flag: false
}
},
mounted() { //当前组件挂载结束,也就是我们可以在页面当中看到真实dom
// mounted这个钩子函数的触发条件是组件创建时会自动触发
// 事件的声明
var _this = this
bus.$on('aa', function() {
_this.flag = true
console.log(this) //这里是this指的是bus, 但是我们需要的this应该是Sma这个组件
})
}
})


new Vue({
el: '#app'
})
### Vue 组件间的通信方法 Vue 提供了多种组件通信的方式,适用于不同的场景和需求。以下是常见的 Vue 组件通信方法及其实现技巧: #### 1. **Props 和 $emit** `props` 是父组件向子组件传递数据的主要方式,而 `$emit` 则用于子组件向父组件发送事件通知。 - 父组件通过 `props` 将数据传递到子组件中[^1]。 - 子组件可以通过调用 `$emit` 方法触发自定义事件,并将数据回传给父组件[^2]。 示例代码如下: ```vue <!-- ParentComponent.vue --> <template> <ChildComponent :message="parentMessage" @childEvent="handleChildEvent" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: 'Hello from Parent', }; }, methods: { handleChildEvent(data) { console.log('Data received from child:', data); } } }; </script> ``` ```vue <!-- ChildComponent.vue --> <template> <div>{{ message }}</div> </template> <script> export default { props: ['message'], mounted() { this.$emit('childEvent', 'Hello from Child'); } }; </script> ``` --- #### 2. **Provide 和 Inject** `provide/inject` 主要用于跨多层嵌套的父子组件之间共享状态,适合全局配置或深层嵌套的情况。 示例代码如下: ```javascript // ParentComponent.vue export default { provide() { return { sharedState: this.sharedState, }; }, data() { return { sharedState: 'Shared Data', }; }, }; // DeeplyNestedChildComponent.vue export default { inject: ['sharedState'], created() { console.log(this.sharedState); // 输出 "Shared Data" }, }; ``` --- #### 3. **v-model (双向绑定)** `v-model` 实现了父子组件之间的双向绑定,通常用于表单输入控件。 示例代码如下: ```vue <!-- ParentComponent.vue --> <template> <CustomInput v-model="inputValue" /> </template> <script> import CustomInput from './CustomInput.vue'; export default { components: { CustomInput }, data() { return { inputValue: '', }; }, }; </script> ``` ```vue <!-- CustomInput.vue --> <template> <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" /> </template> <script> export default { props: ['modelValue'], }; </script> ``` --- #### 4. **Vuex (集中式状态管理)** 对于复杂的大型项目,推荐使用 Vuex 来统一管理和分发状态。 示例代码如下: ```javascript // store.js import { createStore } from 'vuex'; const store = createStore({ state: { count: 0, }, mutations: { increment(state) { state.count++; }, }, }); export default store; ``` ```vue <!-- AnyComponent.vue --> <template> <button @click="increment">Increment Count</button> {{ count }} </template> <script> export default { computed: { count() { return this.$store.state.count; }, }, methods: { increment() { this.$store.commit('increment'); }, }, }; </script> ``` --- #### 5. **Mitt 或 Event Bus** 如果不想引入 Vuex,可以使用轻量级库 Mitt 创建一个简单的事件总线来处理非父子关系的组件通信。 示例代码如下: ```javascript // eventBus.js import mitt from 'mitt'; const emitter = mitt(); export default emitter; // ComponentA.vue emitter.emit('custom-event', payload); // ComponentB.vue emitter.on('custom-event', handlerFunction); ``` --- #### 6. **Expose/Ref** 在组合式 API 中,`ref` 可以用来访问子组件实例中的公开属性或方法,配合 `defineExpose` 使用。 示例代码如下: ```vue <!-- ParentComponent.vue --> <template> <ChildComponent ref="childRef" /> </template> <script setup> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; const childRef = ref(null); function callChildMethod() { childRef.value?.publicMethod(); } </script> ``` ```vue <!-- ChildComponent.vue --> <script setup> defineExpose({ publicMethod() {}, }); </script> ``` --- #### 7. **Attrs 和 Listeners** 当某些属性未被声明为 `props` 时,它们会自动成为 `attrs` 并向下传播;类似的还有 `$listeners`,不过在 Vue 3 中已被移除并替换为 `v-on`。 示例代码如下: ```vue <!-- GrandParentComponent.vue --> <template> <ParentComponent customAttr="test" @customEvent="handleCustomEvent" /> </template> ``` ```vue <!-- ParentComponent.vue --> <template> <ChildComponent v-bind="$attrs" v-on="$listeners" /> </template> <script> export default { inheritAttrs: false, // 防止 attrs 被挂载到根节点上 }; </script> ``` --- #### 总结 以上列举了几种主流的 Vue 组件通信方式,每种都有其适用范围和特点。开发者应根据具体业务需求选择合适的方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值