首页 > 解决方案 > Vue2Js:是否可以调用具有来自另一个组件的属性的方法?

问题描述

我有 3 个组件:组件 1 是顶部菜单,组件 2 是一种具有功能的库,组件 3 是主要代码。

理想情况下,我想在组件 1 中使用组件 2 中的方法和组件 3 中的属性。然后在组件 3 中使用组件 1。

// Component 1 Top Menu
Vue.component('component1', {
    props: {
        titleTest: {
            type: String,
            required: true
        },
        textTest: {
            type: String,
            required: true
        }
    },
    template: `
    <div>
        <div :title="titleTest">{{ titleTest }}</div>
        <div :data-test="textTest">{{ textTest }}</div>
        <button id='test' type="submit" @click="bar">TestButton</button>
    </div>
    `,
    created() {
        console.log('Created1');
        this.$root.$refs.component1 = this;
    },
    methods: {
        //alertText should be passed from Component 3
        bar: function(alertText) {
            console.log(alertText);
            this.$root.$refs.component2.foo(alertText);
        }
    }
});

// Component 2 Lib
Vue.component('component2', {
    created() {
        this.$root.$refs.component2 = this;
    },
    methods: {
        foo: function(alertText) {
            alert('this is component2.foo' + alertText);
        }
    }
});

// Component 3 Main Code
Vue.component('component3', {
    template: `
    <div>
        <div>Some text</div>
        <ul>
            <li>List Item1</li>
            <li>List Item2</li>
        </ul>
        <div>
            <component1 ref="component1" :title-test="test1" :text-test="test2"></component1>
        </div>
    </div>
    `,
    data: function() {
        return {
            test1: 'testText1',
            test2: 'testText2',
            alertText: 'alertText'
        };
    },
    created: function() {
    }
});

new Vue({
    el: '#plotlyExample',
});

我不确定这是否可能,尝试使用“发射”但没有奏效。

标签: javascriptvue.js

解决方案


当你调用时Vue.component('component2', {...}),它只是告诉 Vue 关于命名组件,并且不会生成组件实例,因为它的使用方法component2应该被渲染/安装。但我认为,你错误地使用component2,同样,使用 mixins 或提供/拒绝或 vuex 会更好。


推荐阅读