$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!
本文通过具体的Vue实例代码演示了如何使用$parent属性来获取父级组件实例,以及如何使用$children属性来获取子组件实例。并解释了$children返回的是一个数组而非直接的组件实例的原因。
410

被折叠的 条评论
为什么被折叠?



