Vue中$parent 和$children的使用

来源:互联网 发布:阿里云 smtp发不出 编辑:程序博客网 时间:2024/05/20 05:57

$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!

原创粉丝点击