Vue中$parent 和$children的使用

$parent 该组件实例的父级组件实例

$children 该组件实例的子组件实例

上代码

html部分

<div id='box'>          
    <parent ref='pa'>parent>
div>  

script部分

Vue.component('parent',{
    template:`
<h1>父组件h1><child>child>div>`, components:{ 'child':{ template:`
<h2>这是子组件h2>div>` } } }) new Vue({ el:'#box', created:function(){ this.$nextTick(()=> console.log(this.$refs.pa.$parent) //打印的name为即根实例 ) } })

再次测试一下

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.js)