父链
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>
<body>
<div id="demo">
<child-assemly></child-assemly>
{{msg}}
</div>
<script>
//创建子组件
Vue.component('child-assemly',{
template:'<div><button @click="setparentdata">子组件</button></div>',
methods:{
setparentdata:function(){
//获取父级的父级 .$parent.$parent 依次类推
this.$parent.msg='父组件内容已经被修改'
}
}
})
var app = new Vue({
el: '#demo',
data: {
msg:'---父组件内容'
}
})
</script>
</body>
</html>
复制代码
子链
单个子组件 用this.children 使用方法同父链
多个子组件 使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>
<body>
<div id="demo">
<one-assemly ref='a'></one-assemly>
<tow-assemly ref='b'> </tow-assemly>
<three-assemly ref="c"></three-assemly>
<button @click="parentassemly">{{msg}}</button>
</div>
<script>
Vue.component('one-assemly',{
template:'<div><button >子组件a</button></div>',
data:function(){
return{
msg:'one-assemly'
}
}
})
Vue.component('tow-assemly',{
template:'<div><button >子组件b</button></div>',
data:function(){
return{
msg:'tow-assemly'
}
}
})
Vue.component('three-assemly',{
template:'<div><button >子组件c</button></div>',
data:function(){
return{
msg:'three-assemly'
}
}
})
var app = new Vue({
el: '#demo',
data: {
msg:'未拿到'
},
methods:{
parentassemly:function(){
this.msg=this.$refs.c.msg
}
}
})
</script>
</body>
</html>
复制代码