1.父組件到子組件
父組件 -- > 子組件,使用的props屬性傳遞機制。
-
在父組件調用子組件時,設置屬性
Vue.component(
'child', {
// 聲明 props
props: [
'message'],
// 就像 data 一樣,prop 可以用在模板內
// 同樣也可以在 vm 實例中像 “this.message” 這樣使用
template:
'<span>{{ message }}</span>'
})
設置message屬性的值為hello
<child message="hello!"></child>
結果為 hello!
2. 在子組件中,需要定義屬性
在子組件的定義中,需要使用props選項,來設置可以從父組件中傳遞過來的屬性。
components:{
'my-header':{
template:"#t1",
props:['info']
}
}
3.在子組件中,直接使用
<template id="t1"> <div> <h2>這是子組件</h2> <p>{{info}}</p> </div> </template>
2.子組件到父組件
要實現子組件到父組件之間的通信 ----- 事件機制
分兩步:1.在子組件中,需要發射事件,使用$emit實現。2.在父組件中,需要注冊事件,使用$on 實現
第一步,在子組件中發射事件
//注冊keyup事件
<input type="text" placeholder="輸入用戶名" v-model="username" @keyup="send(username)">
//在子組件中定義send方法
components : { "my-form" : { template : "#t1", data : function(){ return { username : "" } }, methods : { send : function(msg){ //此時,子組件應該向外發生一個事件 this.$emit('transfer',msg); } } } }
第二步,在父組件注冊事件
<h2>父組件</h2>
<p>來自子組件的輸入數據:{{msg}}</p>
<hr>
<my-form @transfer="getUsername"></my-form>
//在父組件中,來定義整個getUsername方法,
methods : { getUsername : function(e){ // alert('ok'); // console.log(e); this.msg = e; } },
然后就可以在父組件中使用{{msg}}