全局事件总线原理:利用自定义事件实现
-
在main.js中安装全局事件总线
import Vue from 'vue'; import App from 'App.vue'; new Vue({ render: h => h(App), beforeCreate() { // 在Vue实例创建之前安装全局事件总线 Vue.prototype.$bus = this; } }).$mount('#app');
-
在需要接收数据的组件中定义、解绑自定义事件
<!-- 需要接收数据的组件 --> <template></template> <script> export default { methods: { getValue(value) { console.log('接收到的数据为:' + value); } }, mounted() { this.$bus.$on('zidingyiEvent', this.getValue); }, beforeDestroy() { this.$bus.$off('zidingyiEvent'); } } </script>
-
在需要发送数据的组件中触发自定义事件
<template> <div> <button @click="send">点击传递数据</button> </div> </template> <script> export default { data() { return { person: { name: 'wuwu', age: 18 } } }, methods: { send() { this.$bus.$emit('zidingyiEvent', this.person); } } } </script>