項目結構:
1.事件總線方式:
①.先建util目錄,然後再目錄裏新建bus.js文件,bus.js文件內容:
//非父子組件傳值之事件總線。 //先建一個bus.js文件,然後在需要傳遞信息的地方引入。 //import bus from './bus.js' //類似C#中定義一個類,然後實例化這個類,然後引用。 import Vue from 'vue' export default new Vue;
②.在需要傳遞信息的組件中引入bus.js,這裏是從APP.vue組件向Child.vue組件傳遞信息,然後要發送數據到Child.vue組件中。
傳遞信息使用 bus.$emit("方法名"),接收信息的組件中使用bus.$on("方法名",callback)監聽
<template> <div id="app"> <button @click="sendmsg">bus走你</button> <m-parent></m-parent> <router-view></router-view> </div> <!-- <router-view/> --> </template> <script> //引入組件 import MParent from './views/Parent' //從app.vue 往 Child.vue中傳遞信息。 import bus from './util/bus'; export default({ components: { MParent,//註冊組件。 }, methods: { sendmsg() { bus.$emit('appmsg','I am from App.vue'); } }, }) </script> <style> </style>
③.在Child.vue組件中引入bus.js,然後監聽bus.$on();
<template> <div> <h3>child</h3> <h4>{{msg}}</h4> <h6>{{childmsg}}</h6> <button @click="sendmsg">傳給父親</button> </div> </template> <script> import bus from '../util/bus'; export default { //使用 props 屬性接收父組件傳過來的值。 props: { msg: { type: String, default: '' }, }, methods: { sendmsg() { this.$emit('showmsg','from child msg');//觸發父組件監聽的showmsg(),並且傳值。 } }, data() { return { childmsg: '' } }, mounted () { bus.$on('appmsg',(val)=>{ this.childmsg=val; }); }, } </script> <style scoped> </style>