<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>componentParentChildCommunication</title>
<script src="js/vue.js"></script>
</head>html
<template id="parentComp">
<div>
I am parent component:{{msg}},The Data from child:{{msg2}}
<hr>
<!-- <child @自定義事件名="父方法"></child> -->
<child @child="parentFn"></child>
</div>
</template>vue
<template id="childComp">
<div>I am child component:{{msg}}</div>
</template>
<body>app
<script>
let child={
template:'#childComp',
data(){
return {
msg:'child Data'
}
},
mounted(){
/*this.$emit('自定義事件名',數據);*/
this.$emit('child',this.msg);
}
};
let parent={
template:'#parentComp',
data(){
return {
msg:'parent Data',
msg2:''
}
},
components:{
child
},
methods:{
parentFn(data){
this.msg2=data;
}
}
};函數
window.onload=function(){
new Vue({
el:'#app',
components:{
parent
}
});
}
/*父元素向子元素通訊關鍵總結:
1:在嵌套的子元素(使用時)上:<child @自定義事件名="父方法"></child>;
2:子元素在加載完成的鉤子函數(mounted)上加一個方法:this.$emit('自定義事件名',數據);
3:父元素上的方法:父方法名(data){...}
*/
</script>this
<div id="app">
<parent></parent>
</div>
</body>
</html>component