Vue兩個同級組件傳值實(shí)現(xiàn)
Vue組件之間是有聯(lián)系的,避免不了組件之間要互相傳值,父給子使用v-bind綁定自定義屬性和使用props來接受
子給父使用@自定義事件=’函數(shù)’ this.$emit(’自定義事件’,’要發(fā)送的內(nèi)容’),子組件通過$emit來觸發(fā)父組件的函數(shù)來實(shí)現(xiàn)但是兩個同級組件之間這么互相傳值
<div id=’app’> <children1></children1> <children2></children2></div><script> var children1 = {}; var children2 = {}; var vm = new Vue({ el:’#app’, components:{ children1, children2 } })</script>
現(xiàn)在要將children1組件中的數(shù)據(jù)傳給children2組件
主要使用到vue實(shí)例中的$on()和$emit()
<div id=’app’> <children1></children1> <children2></children2> </div> <script> var Event = new Vue({}); // 創(chuàng)建一個vue實(shí)例用來作為傳值的媒介 var children1 = { template:` <div> <button @click=’send’>點(diǎn)我給children2組件發(fā)送數(shù)據(jù)</button> </div> `, data(){ return { msg:’我是要給children2發(fā)送的數(shù)據(jù)’ } }, methods:{ send(){ Event.$emit(’go’,this.msg) } } }; var children2 = { template:` <div> <h2>從children1組件接收到的值:{{msg1}}</h2> </div> `, data(){ return{ msg1:’’ } }, created(){ Event.$on(’go’,(v) => { // 必須使用箭頭函數(shù)因?yàn)閠his this.msg1 = v; }) } }; var vm = new Vue({ el:’#app’, components:{ children1, children2 } })</script>
chilren1組件要發(fā)送數(shù)據(jù)使用的是Event.$emit()chilren2組件要接收數(shù)據(jù)使用Eevent.$on()
到此這篇關(guān)于Vue兩個同級組件傳值實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vue 同級組件傳值內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法2. Nginx+php配置文件及原理解析3. windows服務(wù)器使用IIS時thinkphp搜索中文無效問題4. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法5. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析6. 淺談python出錯時traceback的解讀7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)9. Python importlib動態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼10. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向
