子組件通過$emit()事件想父組件發射數據
頁面結構:其中child-a爲子組件:
<template>
<div>
<p>這是父組件</p>
<p>父組件數據1:{{msg}}</p>
<p>父組件數據2:{{json}}</p>
<p>子元素髮送的數據:{{child}}</p>
<p>接受子組件數據:{{receive}}</p>
<hr>
<child-a :msg="msg" :json="json" @childEvent="showChildData"></child-a>
</div>
</template>
data數據:
data(){
return{
msg:"This is parent data!",
json:{name:'data 2!'},
child:'暫無',
receive:'暫無'
}
},
child-a:
<template>
<div>
<p>我是子元素:childA</p>
<p>從父元素處獲取數據1:{{newMsg}}</p>
<p>從父元素處獲取數據2:{{json}}</p>
<p>childA自己的數據:{{self}}</p>
<button @click="changeParentData1">更改父元素的數據1</button>
<button @click="changeParentData2">更改父元素的數據2</button>
<button @click="transferData">將自己的數據發送給父元素</button>
<button @click="transfer">發送自己的數據</button>
</div>
</template>
data數據:
data(){
return {
newMsg:'',
self:"This is Child's data!"
}
},
由於vue2.x不能直接對從父級獲取的數據進行更改,會報錯,這裏額外給一個變量,用來存放從父級那裏獲取的msg
mounted(){
this.newMsg=this.msg;
},
child-a裏面設置props,用來存放從父級拿回來的數據:
props:['msg','json'],
注意:在<child-a :msg="msg" :json="json" @childEvent="showChildData"></child-a>中 屬性名必須與props裏面的一致。
至此,在父級中更改對應的數據,子組件也會發生變化,證明,父組件的數據已經傳遞給了子組件
子組件更改父組件的兩種方法
1.由於不能直接進行更改,所以只能藉助自己的數據來更改,如上述例子,更改newMsg即可,但是此時更改,只有子組件裏面發生變化,父組件不變
methods:{
changeParentData1(){
this.newMsg="數據1被改了"
}
}
2.由於async被廢棄,若想在子組件中更改數據同時把父組件中的數據也更改掉,可以將數據以json的格式傳遞,在子組件中可直接對其更改
methods:{
changeParentData2(){
this.json.name="data2 changed!"
}
}
父組件向子組件的方法,實質上都是通過$emit()時間來發送,這裏提供兩種使用
1.組件上直接通過時間綁定來調用
child-a中,進行數據發射:
child-a中,進行數據發射:
transferData(){
this.$emit('childEvent',this.self);
},
組件通過v-on調用:
<child-a :msg="msg" :json="json" @childEvent="showChildData"></child-a>
methods:{
showChildData(data){
this.child=data;
}
}
2.藉助新的VUE實例將數據掛載在這個新的VUE實例上
var tempVm = new Vue();
在child-a中:事件名爲:childA-data
methods:{
transfer(){
tempVm.$emit('childA-data',this.self);
}
}
其他地方通過$on(name,callback)調用,此處父組件中:
mounted(){
tempVm.$on('childA-data',function(data){
this.receive=data;
}.bind(this));
},
注意:藉助新的vue實例的時候,必須保證這個實例是全局的。