Vue中$parent 和$children的使用
$parent 该组件实例的父级组件实例$children 该组件实例的子组件实例上代码html部分<div id='box'><parent ref='pa'></parent></div>script部分Vue.component('parent',{template:`<div><h1>父组件</h1><child></child></div>`,
·
$parent 该组件实例的父级组件实例
$children 该组件实例的子组件实例
上代码
html部分
<div id='box'>
<parent ref='pa'></parent>
</div>
script部分
Vue.component('parent',{
template:`<div><h1>父组件</h1><child></child></div>`,
components:{
'child':{
template:`<div><h2>这是子组件</h2></div>`
}
}
})
new Vue({
el:'#box',
created:function(){
this.$nextTick(()=>
console.log(this.$refs.pa.$parent) //打印的name为<Root>即根实例
)
}
})
再次测试一下
new Vue({
el:'#box',
created:function(){
this.$nextTick(()=>
console.log(this.$refs.pa.$parent==this) //显示为true
)
}
})
测试一下$children
new Vue({
el:'#box',
created:function(){
this.$nextTick(()=>
console.log(this.$refs.pa.$children) //显示为一个数组
)
}
})
为什么不直接是一个组件实例呢?
再次看了看Vue的API。原来$children的数据类型就是Array!
更多推荐
已为社区贡献11条内容
所有评论(0)