您将要使用
$root
到
$emit
一个事件并倾听
$on
也是。
在你的应用程序中的任何地方简单使用;
this.$root.$emit('myCustomEvent', 'hello world')
/* somewhere else in your app */
this.$root.$on('myCustomEvent', (msg) => {
/* handle the custom event */
console.log(msg)
})
完整示例
<!-- src/App.vue -->
<template lang="html">
<div>
<router-link to="page">Go to Page</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app',
mounted () {
this.$root.$on('pageEvent', handlePageEvent)
},
beforeDestroy () {
// make sure you cleanup the event
this.$root.$off('pageEvent', handlePageEvent)
},
methods: {
handlePageEvent (ev) {
console.log('you clicked me from within')
}
}
}
</script>
<!-- src/Page.vue -->
<template>
<div>
<a @click="$root.$emit('pageEvent')">Click Me</a>
</div>
</template>