1、创建中央事件总线:额外的 new Vue()
2、$emit 触发事件
3、$on 监听事件
在使用组件的文件中:
<template>
<div>
<x-test :bus="bus"></x-test>
<x-right :bus="bus"></x-right>
</div>
</template>
import Vue from ‘vue‘
export default {
data () {
return {
username: ‘xissazi‘,
bus: new Vue()
}
}
}
子组件 <x-right>触发事件:
<template>
<div>
<button @click="add">增加</button>
</div>
</template>
<script>
export default {
data() {
return {
num: 1
}
},
props: [‘bus‘],
methods: {
add: function () {
let n = this.num++
this.bus.$emit(‘otherEvent‘, n)
}
}
}
</script>
子组件 <x-test>:
<template> <div> {{ num }} </div> </template> <script> export default { data () { return { num: 0 } }, props:[‘name‘, ‘bus‘], mounted() { let that = this this.bus.$on(‘otherEvent‘, function(val){ that.num = val }) } } </script>
原文:https://www.cnblogs.com/yuyedaocao/p/11981638.html