vue組件與組件通信有如下幾種情況:
平行組件
父組件與子組件
子組件與父組件
它們之間通信有幾種方法有:
props
自定義事件
vuex
今天我們聊一下父組件調(diào)用子組件的一種方法
parent.vue
<template>
? ? <div>
? ? ? ? <h1>我是父組件</h1>
? ? ? ? <child ref="child"></child>
? ? </div>
</template>
<script>
? ? import child from './child'
? ? export default{
? ? ? ? components:{ child },
? ? ? ? methods:{
? ? ? ? ? ? parent(){
? ? ? ? ? ? ? ? this.$.refs.child.childFn()
? ? ? ? ? ? }
? ? ? ? }
? ? }
</script>
child.vue
<template>
? ? <div>
? ? ? <h2>我是子組件</h2>
? ? </div>
</template>
<script>
? ? import child from './child'
? ? export default{
? ? ? ? components:{ child },
? ? ? ? methods:{
? ? ? ? ? ? childFn(){
? ? ? ? ? ? ? ? alert('父組件調(diào)用了我')
? ? ? ? ? ? }
? ? ? ? }
? ? }
</script>
1.父組件傳遞數(shù)據(jù)給子組件
父組件數(shù)據(jù)如何傳遞給子組件呢?可以通過props屬性來實現(xiàn)
父組件:
<parent>
? ? <child :child-msg="msg"></child>? //這里必須要用 - 代替駝峰
</parent>
data(){
? ? return {
? ? ? ? msg: [1,2,3]
? ? };
}
子組件通過props來接收數(shù)據(jù):
方式1:
props: ['childMsg']
方式2 :
props: {
? ? childMsg: Array //這樣可以指定傳入的類型,如果類型不對,會警告
}
方式3:
props: {
? ? childMsg: {
? ? ? ? type: Array,? ? //傳入的類型
? ? ? ? default: [0,0,0] //這樣可以指定默認的值
? ? }
}
2.子組件與父組件通信
子組件:
<template>
? ? <div @click="testClick"></div>
</template>
methods: {
? ? testClick() {
? ? ? ? this.$emit('test','123'); //$emit(even,value)even 是一個函數(shù),value 是傳給父組件的值? ? ? , 觸發(fā)名為test方法, '123'為向父組件傳遞的數(shù)據(jù)
? ? }
}
父組件接收:?
<div>
? ? <child @test="change" :msg="msg"></child>? //監(jiān)聽子組件觸發(fā)的test事件,然后調(diào)用change方法
</div>
methods: {
? ? change(val) {
? ? ? ? this.msg = val;? // val: 123
? ? }
}
3.非父子組件通信
如果2個組件不是父子組件那么如何通信呢?這時可以通過eventHub來實現(xiàn)通信.
所謂eventHub就是創(chuàng)建一個事件中心,相當(dāng)于中轉(zhuǎn)站,可以用它來傳遞事件和接收事件.
let Hub = new Vue(); //創(chuàng)建事件中心
組件1觸發(fā):
<div @click="eve"></div>
methods: {
? ? eve() {
? ? ? ? Hub.$emit('change','hehe'); //Hub觸發(fā)事件
? ? }
}
組件2接收:
<div></div>
created() {
? ? Hub.$on('change', () => { //Hub接收事件
? ? ? ? this.msg = 'hehe';
? ? });
}