vue.js中使用props down,events up的原則進行父子組件間的通信,先來記錄下props down,看個例子:
<div id="app2">
<child message="hello!"></child>
</div>
...
Vue.component('child', {
// 聲明 props
props: ['message'],
// 就像 data 一樣,prop 可以用在模板內
// 同樣也可以在 vm 實例中像 “this.message” 這樣使用
template: '<span>{{ message }}</span>'
})
new Vue({
el:"#app2"
});
以上定義了一個全局組件child,在app2的父級作用域中使用時,child組件定義了一個message屬性,這樣父組件在使用子組件的地方直接通過給child的message屬性賦值即可將該值傳遞到子組件內部,從而輸出模板內容:hello!,這里的“hello!”字符串是固定的,如果我們想傳入的是app2作用域中的動態數值可以使用如下方式:
<div id="app2">
<child v-bind:message="parentMsg"></child>
<input v-model="parentMsg">
</div>
...
Vue.component('child', {
// 聲明 props
props: ['message'],
// 就像 data 一樣,prop 可以用在模板內
// 同樣也可以在 vm 實例中像 “this.message” 這樣使用
template: '<span>{{ message }}</span>'
})
new Vue({
el:"#app2",
data:{
parentMsg:""
}
});
這樣的話,子組件中的message值完全來自於父組件中的data.parentMsg,父組件的數據操作直接更新到子組件中。
再來看下events up的實例:
<div id="counter-event-example">
<p>{{ total }}</p>
<!-- 父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件,也就是這里的$.emit("increment")事件 -->
<button-counter v-on:increment2total="incrementTotal"></button-counter>
<button-counter v-on:increment2total="incrementTotal"></button-counter>
</div>
...
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment2total',{"admin":"############"})
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function (value) {
alert(JSON.stringify(value));
this.total += 1
}
}
})
子組件模板中聲明click事件,調用自身methods方法increment,increment里面通過$emit形式拋出一個事件到對應的子組件:on那里,查找到對應的父組件調用方法為incrementTotal,則直接調用該方法並傳遞參數。
關於vue.js后續一些學習心得體會均會在此處分享,一步步慢慢學吧。。。
