组件之间的通信
自定义事件
在Vue中子组件使用$emit()
来触发事件,父组件使用$on()
来监听事件。
父组件也可以直接在子组件的自定义标签上使用v-on
来监听子组件触发的自定义事件
<template>
<div class="examples">
<p class="total-count">总数<span>{{total}}</span></p>
<my-component @increase="handleGetTotal" @reduce="handleGetTotal" @click.native="handleClick"></my-component>
</div>
</template>
<script>
import Vue from 'vue'
Vue.component('my-component', {
data() {
return {
counter: 0
}
},
methods: {
handleIncrease() {
this.counter ++
this.$emit('increase', this.counter)
},
handleReduce() {
this.counter --
this.$emit('reduce', this.counter)
}
},
render(cr) {
return cr(
'div', {'class': 'child-wrap'},[
cr('button', {attrs: {'class': 'btn'},on: {click: this.handleIncrease}},['+1']),
cr('button', {attrs: {'class': 'btn'},on: {click: this.handleReduce}}, ['-1'])
]
)
}
})
export default {
data() {
return {
total: 0
}
},
methods: {
handleGetTotal(counter) {
this.total = counter
},
handleClick(ev) {
console.log(ev)
}
}
}
在上面的例子中,父组件用v-on:increase
和v-on:reduce
来监听子组件的自定义事件increase
和reduce
,子组件使用$emit()
来触发事件,其中第一个参数是自定义事件的名称,后面可选参数都是要传递的数据,可以传递多个。
使用.native
修饰符表示监听原生的DOM事件。
非父子组件之间的通信
在兄弟组件,跨级组件之间通信,一般使用一个空的Vue实例
来实现
<template>
<div class="message">
<span class="msg">{{message}}</span>
<my-component></my-component>
</div>
</template>
<script>
import Vue from 'vue'
let bus = new Vue()
Vue.component('my-component', {
data() {
return {
msg: 'this is from child message!'
}
},
methods: {
handleEvent() {
bus.$emit('on-message', this.msg)
},
},
render(cr) {
return cr('div',{on: {click: this.handleEvent}}, ['传递事件'])
}
})
export default {
data() {
return {
message: 'this is a placeholder'
}
},
mounted() {
let _this = this
bus.$on('on-message', function(msg) {
_this.message = msg
})
}
}
</script>
在子组件中通过自定义事件on-message
传递出参数,在父组件mounted
中接收,在回调中根据参数做相应的操作。
在bus
实例中,可以拓展其属性,添加data、methods、computed
等,使其在所有页面共享
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。