Vue-event-bus
by hysunny
HTML
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<nav>
<router-link to="/">Go to A</router-link>
<router-link to="/b">Go to B</router-link>
</nav>
<router-view></router-view>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
Vue
const eventBus = new Vue()
Vue.prototype.$bus = eventBus;
let times = 1;
const A = {
template: '<div>A页面mounted次数: {{ times }}</div>' ,
data() {
return {
times: times
}
},
mounted() {
this.$bus.$emit('A.show', times);
times += 1;
},
beforeDestroy() {
// this.$bus.$off('A.show')
}
}
const B = {
template: '<div>B页面接收到A页面mounted的次数请打开控制台查看</div>',
mounted() {
this.$bus.$on('A.show', (data) => {
console.log(data)
})
}
}
const routes = [
{ path: '/', component: A },
{ path: '/b', component: B }
]
const router = new VueRouter({
routes
})
const app = new Vue({
router,
el: "#app",
data: {},
methods: {}
}).$mount('#app')