美文网首页
父组件主动获取子组件的数据和方法

父组件主动获取子组件的数据和方法

作者: 努力与幸运 | 来源:发表于2019-11-26 10:24 被阅读0次

vue通过v-ref获取到整个组件的对象

<body>
    <div id="app">
        <button @click="getdata">获取dom对象</button>
        <subcom v-ref:mycomp></subcom>  ---指定找的是这个组件
    </div>
    <script>

    //1.0 定义组件
    Vue.component('subcom',{
        template:'<h1>这是subcom子组件内容</h1>',
        data:function(){
            return {
                msg:'hello'
            }
        }
    }); 

    new Vue({
        el:'#app',
        methods:{
            getdata:function(){
                // 获取到subcom这个组件对象
            console.log(this.$refs.mycomp);

            console.log(this.$refs.mycomp.$data.msg);  -----获取到data里的hellow
            }
        }
    });
    </script>
</body>

1.调用子组件的时候 定义一个ref

<headerchild ref="headerChild"></headerchild>

2.在父组件里

this.$refs.headerChild.属性
this.$refs.headerChild.方法

3,在子组件调用父组件的方法

this.$parent.属性
this.$parent.方法

相关文章

网友评论

      本文标题:父组件主动获取子组件的数据和方法

      本文链接:https://www.haomeiwen.com/subject/njcewctx.html