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>`,
    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!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值