項目中,我們經(jīng)常會遇到兄弟組件通信的情況。在大型項目中我們可以通過引入vuex輕松管理各組件之間通信問題,但在一些小型的項目中,我們就沒有必要去引入vuex。下面簡單介紹一下使用傳統(tǒng)方法,實現(xiàn)父子組件通信的方法。
簡單實例:我們在a組件中點擊按鈕,將信息傳給b組件,從而使b組件彈出。
主要的思路就是:先子傳父,在父傳子
首先我們在 a.vue 組件中 ,給按鈕botton綁定一個handleClick事件,事件中我們通過 this.$emit() 方法去觸發(fā)一個自定義事件,并傳遞我們的參數(shù)。
示例中我們通過this.$emit() 去觸發(fā)isLogFn 這個方法自定義事件,并將log 參數(shù)傳遞出去
a.vue
<template> <div class="adiv"> <p>a組件</p> <button type="button" v-on:click="handleClick">點擊打開組件b彈窗</button> </div> </template> <script> export default { methods: { handleClick () { this.$emit('isLogFn','log') } } } </script> <style> .adiv{ width: 400px; height: 200px; border: 1px solid #000; margin: 0 auto; } </style>
第二步,我們要在父組件中去監(jiān)聽這個自定義事件,去觸發(fā)對應(yīng)的方法,并接受a組件傳過來的參數(shù)。此時我們就完成了子組件向父組件傳值的過程。
示例中,<aPage @isLogFn = "lisLogFn"></aPage> 監(jiān)聽isLogFn 去觸發(fā)我們在父組件中定義的方法lisLogFn,并拿到傳過來的 ‘log' 數(shù)據(jù)。完成子父傳值。
到此,整個過程還沒有結(jié)束,只是完成了一半。接下來我們要完成父子組件傳值,將a組件的信息在傳給b組件。
在< bPage > 標簽中綁定islog 屬性,動態(tài)綁定data中的login 字段,在我們通過lisLogFn 方法拿到 ‘data'之后,我們要判斷 data 傳過來的數(shù)據(jù),根據(jù)判斷結(jié)果去改變data()中的數(shù)據(jù),從而將數(shù)據(jù)傳遞給b組件
App.vue
<template> <div id="app"> <aPage @isLogFn = "lisLogFn"></aPage> <bPage :isLog = "login"></bPage> </div> </template> <script> import aPage from './components/a.vue' import bPage from './components/b.vue' export default { data () { return { login: 'false' } }, name: 'app', components: { aPage, bPage }, methods: { lisLogFn (data) { if (data == 'log') { this.login = 'true' } } } } </script> <style> </style>
最后,b組件中需要創(chuàng)建props,定義一個isLog 屬性,這個屬性就是我們傳過來的數(shù)值。然后我們在計算屬性中處理這個數(shù)據(jù),最終供b組件使用。示例中,我們在v-show="isLogin" 中用來控制彈窗是否打開。
切記!不能直接使用這個props,一定要經(jīng)過computed處理,原因我引用vue官方說明
單向數(shù)據(jù)流
b.vue
<template> <div class="bdiv" v-show="isLogin">我是組件B彈窗</div> </template> <script> export default { props: ['isLog'], data () { return { } }, computed: { isLogin () { if(this.isLog == 'true'){ return true } else { return false } } } } </script> <style> .bdiv{ width: 200px; height: 200px; border: 1px #000 solid; margin: 0 auto; } </style>
總結(jié): 想要實現(xiàn)兄弟組件傳值,一定要首先熟悉子父,父子之間的傳值。
子父:
父子:
文中示例 github 地址:https://github.com/enjoy-pany/vue-emit
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com