使用Bus實現跨組件傳輸須注意以下3點:
1.需要創建一個空的Vue實例(bus),來作為中間站
2.使用bus.emit來發送事件3.使用bus.emit來發送事件 3.使用bus.emit來發送事件3.使用bus.on來監聽事件(在鉤子created中監聽)
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body><div id="app"><p>{{ message }}</p><my-component></my-component>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>const bus = new Vue({});Vue.component('my-component',{template:'<button @click="sendMessage">派發事件</button>',methods:{sendMessage:function() {bus.$emit('on-message', '使用bus派發的事件');},}})const app = new Vue({el:'#app',data:{message: ''},mounted:function(){let self = this;bus.$on('on-message',function(msg){self.message = msg;})}})
</script>
</body>
</html>
參考《Vue.js實戰》P80