这篇文章vue.js组件的通信之父组件向子父组件的通信(代码)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>componentparentchildcommunication</title>
<script src="js/vue.js"></script>
</head>
<template id="parentcomp">
<p>
i am parent component:{{msg}},the data from child:{{msg2}}
<hr>
<!-- <child @自定义事件名="父方法"></child> -->
<child @child="parentfn"></child>
</p>
</template>
<template id="childcomp">
<p>i am child component:{{msg}}</p>
</template>
<body>
<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>
<p id="app">
<parent></parent>
</p>
</body>
</html>
以上就是vue.js组件的通信之父组件向子父组件的通信(代码)的详细内容。