總結:
父組件--》子組件
①經過屬性
步驟1:
<son myName="michael" myPhone='123'></son>
<son :myName="userList[0]"></son>
步驟2:
Vue.component('son',{
props:['myName','myPhone']
})
②經過$parent
直接在子組件中經過this.$parent獲得調用子組件的父組件html
子組件--》父組件
①events up
步驟1:在父組件中 調用子組件的時候 綁定一個自定義事件 和 對應的處理函數
methods:{
recvMsg:function(msg){
//msg就是傳遞來的數據
}
},
template:'
<son @customEvent="recvMsg"></son>
'vue
步驟2:在子組件中 把要發送的數據經過觸發自定義事件傳遞給父組件
this.$emit('customEvent',123)函數
②$refsthis
reference 引用
步驟1:在調用子組件的時候 能夠指定ref屬性
<son ref='zhangsan'></son>
步驟2:經過$refs獲得指定引用名稱對應的組件實例
this.$refs.zhangsanspa
兄弟組件通訊
步驟1:建立一個Vue的實例 做爲事件綁定觸發的公共的對象
var bus = new Vue();
步驟2:在接收方的組件 綁定 自定義的事件
bus.$on('customEvent',function(msg){
//msg是經過事件傳遞來的數據 (傳遞來的123)
});
步驟3:在發送方的組件 觸發 自定義的事件
bus.$emit('customEvent',123);code
每日一練:component
建立2個組件,main-component,son-componenthtm
視圖:
main-component 顯示一個按鈕
son-component 顯示一個p標籤對象
功能:
main-component 定義一個變量count,初始化爲0,將count傳遞給son-component,son-component接收到數據顯示在p標籤中blog
main-component 在點擊按鈕時,實現對count的自增操做,要求son-component可以實時顯示count對應的數據
son-component在接收到count以後,在count大於10的時候,將main-component的按鈕禁用掉
(參考:<button v-bind:disabled="!isValid">clickMe</button>)
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>小練習</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <main-component></main-component> </div> <script> /* 每日一練: 建立2個組件,main-component,son-component 視圖: main-component 顯示一個按鈕 son-component 顯示一個p標籤 功能: main-component 定義一個變量count,初始化爲0,將count傳遞給son-component,son-component接收到數據顯示在p標籤中 main-component 在點擊按鈕時,實現對count的自增操做,要求son-component可以實時顯示count對應的數據 son-component在接收到count以後,在count大於10的時候,將main-component的按鈕禁用掉 (參考:<button v-bind:disabled="!isValid">clickMe</button>) */ //建立父組件 Vue.component("main-component",{ data:function(){ return { count:0, isDisabled:true } }, methods:{ //點擊按鈕對count進行自增 //並經過$emit觸發countAdd,並把count的值傳遞給子組件 //判斷count==10的時候讓按鈕禁用 countAdd:function(){ this.count++; console.log("對數據進行自增:"+this.count); this.$emit("countAdd",this.count); } }, template:` <div> <button @click="countAdd" v-bind:disabled="!isDisabled">點我</button> <son-component v-bind:myCount="count"></son-component> </div> ` }) //建立子組件 Vue.component("son-component",{ //經過props接收父組件傳遞過來的值 props:["myCount"], template:` <div> <p>{{myCount}}</p> </div> `, //數據更新完成後判斷從父組件拿到的值 updated:function(){ if(this.myCount>10){ //子組件經過$parent直接獲取父組件的數據 this.$parent.isDisabled = false; } } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>