簡(jiǎn)單實(shí)例:我們?cè)赼組件中點(diǎn)擊按鈕,將信息傳給b組件,從而使b組件彈出。
主要的思路就是:先子傳父,在父?jìng)髯?/p>
首先我們?cè)?a.vue 組件中 ,給按鈕botton綁定一個(gè)handleClick事件,事件中我們通過(guò) this.$emit() 方法去觸發(fā)一個(gè)自定義事件,并傳遞我們的參數(shù)。
示例中我們通過(guò)this.$emit() 去觸發(fā)isLogFn 這個(gè)方法自定義事件,并將log 參數(shù)傳遞出去
a.vue
<template> <p class="ap"> <p>a組件</p> <button type="button" v-on:click="handleClick">點(diǎn)擊打開(kāi)組件b彈窗</button> </p> </template> <script> export default { methods: { handleClick () { this.$emit('isLogFn','log') } } } </script> <style> .ap{ width: 400px; height: 200px; border: 1px solid #000; margin: 0 auto; } </style>
第二步,我們要在父組件中去監(jiān)聽(tīng)這個(gè)自定義事件,去觸發(fā)對(duì)應(yīng)的方法,并接受a組件傳過(guò)來(lái)的參數(shù)。此時(shí)我們就完成了子組件向父組件傳值的過(guò)程。
示例中,<aPage @isLogFn = "lisLogFn"></aPage> 監(jiān)聽(tīng)isLogFn 去觸發(fā)我們?cè)诟附M件中定義的方法lisLogFn,并拿到傳過(guò)來(lái)的 ‘log' 數(shù)據(jù)。完成子父?jìng)髦怠?/p>
到此,整個(gè)過(guò)程還沒(méi)有結(jié)束,只是完成了一半。接下來(lái)我們要完成父子組件傳值,將a組件的信息在傳給b組件。
在< bPage > 標(biāo)簽中綁定islog 屬性,動(dòng)態(tài)綁定data中的login 字段,在我們通過(guò)lisLogFn 方法拿到 ‘data'之后,我們要判斷 data 傳過(guò)來(lái)的數(shù)據(jù),根據(jù)判斷結(jié)果去改變data()中的數(shù)據(jù),從而將數(shù)據(jù)傳遞給b組件
App.vue
<template> <p id="app"> <aPage @isLogFn = "lisLogFn"></aPage> <bPage :isLog = "login"></bPage> </p> </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組件中需要?jiǎng)?chuàng)建props,定義一個(gè)isLog 屬性,這個(gè)屬性就是我們傳過(guò)來(lái)的數(shù)值。然后我們?cè)谟?jì)算屬性中處理這個(gè)數(shù)據(jù),最終供b組件使用。示例中,我們?cè)趘-show="isLogin" 中用來(lái)控制彈窗是否打開(kāi)。
切記!不能直接使用這個(gè)props,一定要經(jīng)過(guò)computed處理,原因我引用vue官方說(shuō)明
單向數(shù)據(jù)流
b.vue
<template> <p class="bp" v-show="isLogin">我是組件B彈窗</p> </template> <script> export default { props: ['isLog'], data () { return { } }, computed: { isLogin () { if(this.isLog == 'true'){ return true } else { return false } } } } </script> <style> .bp{ width: 200px; height: 200px; border: 1px #000 solid; margin: 0 auto; } </style>
總結(jié): 想要實(shí)現(xiàn)兄弟組件傳值,一定要首先熟悉子父,父子之間的傳值。
子父:
子組件中需要以某種方式例如點(diǎn)擊事件的方法來(lái)觸發(fā)一個(gè)自定義事件
將需要傳的值作為$emit的第二個(gè)參數(shù),該值將作為實(shí)參傳給響應(yīng)自定義事件的方法
在父組件中注冊(cè)子組件并在子組件標(biāo)簽上綁定對(duì)自定義事件的監(jiān)聽(tīng)
父子:
子組件在props中創(chuàng)建一個(gè)屬性,用以接收父組件傳過(guò)來(lái)的值
在子組件標(biāo)簽中添加子組件props中創(chuàng)建的屬性,把需要傳給子組件的值賦給該屬性
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com