Vue兩個同級組件傳值實現(xiàn)
Vue組件之間是有聯(lián)系的,避免不了組件之間要互相傳值,父給子使用v-bind綁定自定義屬性和使用props來接受
子給父使用@自定義事件=’函數(shù)’ this.$emit(’自定義事件’,’要發(fā)送的內(nèi)容’),子組件通過$emit來觸發(fā)父組件的函數(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實例中的$on()和$emit()
<div id=’app’> <children1></children1> <children2></children2> </div> <script> var Event = new Vue({}); // 創(chuàng)建一個vue實例用來作為傳值的媒介 var children1 = { template:` <div> <button @click=’send’>點我給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ù)因為this 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兩個同級組件傳值實現(xiàn)的文章就介紹到這了,更多相關(guān)Vue 同級組件傳值內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 解決Python 進程池Pool中一些坑2. 三個不常見的 HTML5 實用新特性簡介3. Python獲取抖音關(guān)注列表封號賬號的實現(xiàn)代碼4. Python使用jupyter notebook查看ipynb文件過程解析5. ajax請求添加自定義header參數(shù)代碼6. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法7. Python如何讀寫CSV文件8. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究9. php測試程序運行速度和頁面執(zhí)行速度的代碼10. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁
