我將要實現的是:點擊按鈕,將組件2中的數據傳遞給組件1,在組件1中展現。
能夠直接複製執行
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>非父子組件中的通訊</title> <!-- 開發環境版本,包含了有幫助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <style> .componentOne { background-color: greenyellow; border: 1px solid green; width: 250px; height: 80px; margin-left: 20px } .componentTwo { background-color: lightgray; border: 1px solid green; width: 250px; height: 80px; margin-left: 20px } </style> <body> <div id="app"> <component-one></component-one> <component-two></component-two> </div> <script> //在vue上面掛載一個$bus做爲中央處理組件 Vue.prototype.$bus = new Vue() //組件1 var componentOne = { template: '<div class="componentOne">組件1 -- {{fromtwo}}</div>', data() { return { onemsg: '我是組件1的數據', fromtwo: '' //接受從組件2傳過來的數據 } }, created() { //1.這是方法一 /*var self = this //先接受 這個實例中的 this this.$bus.$on('sending',function(val){ //this.fromtwo = val //這裏不了能夠這樣寫,由於在這個做用域中,this表明的是 $bus中 self.fromtwo = val // 這裏的 })*/ //2.也能夠直接用箭頭函數 this.$bus.$on('sending', (val) => { //箭頭函數改變了this的指向 this.fromtwo = val }) }, } //組件2 var componentTwo = { template: `<div class="componentTwo"> 組件2 <button @click="toOne">我要將個人數據傳給組件1</button> </div>`, data() { return { twomsg: '我是組件2的數據', } }, methods: { toOne() { this.$bus.$emit('sending', this.twomsg) } }, } new Vue({ el: '#app', //聲明組件 components: { 'component-one': componentOne, 'component-two': componentTwo, } }) </script> </body> </html>
利用$emit $on的觸發和監聽事件實現非父子組件的通訊javascript
Vue.prototype.$bus=new Vue()//在vue上面掛載一個$bus做爲中央處理組件 this.$bus.$emit('自定義事件名','傳遞的數據')//觸發自定義事件傳遞數據 this.$bus.$on('自定義事件名',fn)//監聽自定義事件獲取數據
從網上了解到,解決的方案還有vuex
、provide/inject
是解決同根往下派發、本地存儲也能夠進行非父子組件之間的通訊
這塊暫時沒學到,待學習。html