<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>parentChildComponent</title>
<script src="js/vue.js"></script>
<template id="parent">
<div>
I am parent component !{{msg}};I accept :{{msg2}}
<hr>
<child ref="child"></child>
</div>
</template>
<template id="child">
<div>
I am child component !{{msg}};I accept :{{msg2}}
</div>
</template>
</head>
<body>
<script>
window.onload=function(){
let child={
template:'#child',
data(){
return {
msg:'Data of child !',
msg2:''
}
},
mounted(){
this.msg2=this.$parent.msg;
}
};
let parent={
template:'#parent',
components:{
child
},
data(){
return {
msg:'Data of parent !',
msg2:''
}
},
mounted(){
this.msg2=this.$refs.child.msg
}
};
new Vue({
el:'#app',
components:{
parent
}
});
}
</script>
<div id="app">
<parent></parent>
</div>
</body>
</html>
打通父子之间所有数据和方法的共享:
父模板:<child ref="子名称"></child>
父访问子:父组件: this.$refs.子名称.子数据/方法名()
子访问父:子组件: this.$parent.子数据/方法名()