Vue 子组件可以通过 $root 属性访问根实例的属性和方法 

Vue 子组件可以通过 $parent属性访问父组件实例的属性和方法

下面写个简单的demo: 

 

<div id="app">
    <first-child></first-child>
</div>

 

Vue.component("first-child", {
    data : function () {
        return {
            msg: "first child data"
        }
    },
    template : "<second-child></second-child>",
    methods: {
    }
});

Vue.component("second-child", {
    data : function () {
        return {
            msg: "second child data"
        }
    },
    template : "<div>this.$root.msg: {{this.$root.msg}}" +
        "<div>this.parent.msg: {{this.$parent.msg}}</div>" +
        "<div>this.msg: {{this.msg}}</div></div>",

    methods: {

    }
});


let vue = new Vue({
    el: "#app",
    data: {
        msg: "root data"
    },
    beforeMount : function(){

    },
    computed:{

    },
    methods: {

    }
});

 

运行,在页面中会看到: 

this.$root.msg: root data

this.parent.msg: first child data

this.msg: second child data

 

简单易懂

Logo

前往低代码交流专区

更多推荐