vue中組件通信方法有很多種,可以根據(jù)具體場(chǎng)景來(lái)選擇具體使用哪種种玛。比較常見(jiàn)的以下幾種方法:
1币他、父組件向子組件傳參
在父組件中向子組件傳入普通字符串:
<Child message="hello vue"></Child>
在子組件中用props接受傳進(jìn)來(lái)的參數(shù):
props: {
message: ''
}
完整代碼:
// 父組件
<template>
<div id="example">
<Child message="hello vue"></Child>
</div>
</template>
<script type="text/javascript">
import Child from './Child';
export default {
components: {
Child
}
}
</script>
// 子組件
<template>
<div id="child">
<span>{{ message }}</span>
</div>
</template>
<script type="text/javascript">
export default {
props: {
message: ''
}
}
</script>
2抽兆、子組件向父組件傳參
props傳遞參數(shù)時(shí)是單向的配喳,這意味著我們不能通過(guò)props向父組件傳遞參數(shù)酪穿。我們可以在子組件中發(fā)送事件,在父組件中監(jiān)聽(tīng)事件來(lái)實(shí)現(xiàn)子組件向父組件傳參界逛。
子組件使用emit發(fā)送事件:
this.$emit('listenFromChildData', 'this message is from child')
父組件監(jiān)聽(tīng)事件:
<Child @listenFromChildData="childData"></Child>
完整代碼:
// 父組件
<template>
<div id="example">
<span>{{text}}</span>
<Child @listenFromChildData="childData"></Child>
</div>
</template>
<script type="text/javascript">
import Child from './Child';
export default {
data: function() {
return {
text: ''
}
},
methods: {
childData(data) {
this.text = data
}
},
components: {
Child
}
}
</script>
// 子組件
<template>
<div>
<button @click="sendMsgToParent">向父組件傳值</button>
</div>
</template>
<script type="text/javascript">
export default {
methods: {
sendMsgToParent() {
// 發(fā)送數(shù)據(jù)
this.$emit('listenFromChildData', 'this message is from child')
}
}
}
</script>
3昆稿、非父子組件通信
非父子組件之間通信時(shí),簡(jiǎn)單的情況下息拜,可以使用事件總線。
首先定義一個(gè)空的Vue實(shí)例作為事件總線:
let bus = new Vue()
在A組件中使用emit發(fā)送事件:
bus.$emit('event', data)
在B組件中使用on監(jiān)聽(tīng)事件:
bus.$on('event', function (data) {
// todo ...
})
完整代碼:
// 組件A
<template>
<div>
<span>組件A</span>
<button v-on:click="add"> {{text}} </button>
</div>
</template>
<script type="text/javascript">
import bus from '../bus.js'
export default {
data: function() {
return {
text: '發(fā)送數(shù)據(jù)',
data: ''
}
},
methods: {
add() {
bus.$emit('sendDataToB', 'this data from A')
}
}
}
</script>
// 組件B
<template>
<div>
<span>組件B</span>
<span>{{data}}</span>
</div>
</template>
<script type="text/javascript">
import bus from '../bus.js'
export default {
data: function() {
return {
data: ''
}
},
mounted() {
var self = this
bus.$on('sendDataToB', function (msg) {
self.data = msg
})
}
}
</script>
4净响、vuex
在復(fù)雜情況下少欺,組件間通信可以使用vuex,vuex的官方文檔