Vue 父子元件及同級元件之間的傳值
阿新 • • 發佈:2018-12-17
1.父元件 father.vue
<template> <div id="father"> <h2>父元件</h2> <p>數值:{{m}}</p> <son1 v-on:giveFather='giveFather'></son1> <son2></son2> </div> </template> <script> import son1 from'./son1' import son2 from './son2' export default { data(){ return { m:'' } }, name:'father', components:{ son1, son2 }, methods:{ giveFather: function(childValue) {// childValue就是子元件傳過來的值 this.m = childValue } } } </script>
2.子元件1 son1.vue
<template> <div id="son1"> <h2>子元件1</h2> <button @click='push'>向兄弟元件傳值</button> <button @click='give'>向father元件傳值</button> </div> </template> <script> import bus from'../../assets/eventBus' export default { methods:{ push(){ bus.$emit("userDefinedEvent","this message is from son1 to son2"); }, give(){ this.$emit('giveFather',"this message is from son1 to father") } } } </script>
3.子元件2 son2.vue
<template> <div id="son2"> <h2>子元件2</h2> <p>數值:{{msg}}</p> </div> </template> <script> import bus from '../../assets/eventBus' export default { data(){ return { msg:'' } }, mounted(){ var self = this; bus.$on("userDefinedEvent",function(msg){ self.msg=msg; }); } } </script>
4.中央事件匯流排
同級元件傳值時,需要新增中央資料匯流排 在src/assets/下建立一個eventBus.js,內容如下
(eventBus中我們只建立了一個新的Vue例項,以後它就承擔起了元件之間通訊的橋樑了,也就是中央事件匯流排。)
import Vue from 'Vue' export default new Vue
5.效果
5.總結
子元件向父元件傳值時,在響應該點選事件的函式中使用$emit來觸發一個自定義事件,並傳遞一個引數。在父元件中的子標籤中監聽該自定義事件並新增一個響應該事件的處理方法 ;
同級元件傳值時,用到bus.$emit和bus.$on兩個自定義事件,並需要建立並新增中央資料匯流排