給大家介紹幾種VUE組件之間通信的方式,根據(jù)業(yè)務(wù)場(chǎng)景大家可以自行選擇。
1、通過$emit讓子組件與父通信
/*
@ 子組件 btn.vue
*/
<template>
<button @click="trigger">{{text}}</button>
</template>
<script>
module.exports = {
data () {
return {}
},
props: {
text: {
type: [String, Number],
default: '確定'
}
},
methods: {
trigger () {
//觸發(fā)一個(gè)名字叫‘hello’的自定義事件, 并傳遞一個(gè)叫str的參數(shù)
var str = 'hello word'
this.$emit('hello', str)
}
}
}
</script>
/*
監(jiān)聽自定義hello事件,并觸發(fā)helloWord方法
*/
<template>
<btn @hello="helloWord"></btn>
</template>
<script>
import btn from 'btn.vue'
module.exports = {
data () {
return {}
},
methods: {
helloWord(str) {
console.log(str)
}
},
components: { btn }
}
</script>
2、通過ref獲取子組件實(shí)例(屬性、方法)
/*
@ 子組件 btn.vue
*/
<template>
<button @click="trigger">{{text}}</button>
</template>
<script>
module.exports = {
data () {
return {
text: '確定'
}
},
methods: {
_init () {
this.text = 'hello word'
}
}
}
</script>
/*
通過ref與子組件通信
*/
<template>
<btn ref="btn"></btn>
</template>
<script>
import btn from 'btn.vue'
module.exports = {
data () {
return {}
},
created () {
//獲取btn實(shí)例
var vueBtn = this.$refs.btn
//調(diào)用_init方法
vueBtn._init()
},
components: { btn }
}
</script>
2、通過一個(gè)空的VUE實(shí)例作為事件總代理,父與子、子與父、兄弟組件之間就可以通信了
/*
@ Event.js
*/
import Vue from 'vue'
export default new Vue()
/*
@ Event.js用法
*/
import Event from 'Event.js'
//事件監(jiān)聽
Event.$on('hello', (str)=> {
console.log(str)
})
//事件觸發(fā)
var str = 'hello, word'
Event.$emit('hello', str)