假设我有一个主Vue实例,它有子组件。是否有一种方法可以完全从Vue实例外部调用属于这些组件之一的方法?

这里有一个例子:

var vm = new Vue({ el: '#app', components: { 'my-component': { template: '#my-template', data: function() { return { count: 1, }; }, methods: { increaseCount: function() { this.count++; } } }, } }); $('#external-button').click(function() { vm['my-component'].increaseCount(); // This doesn't work }); <script src="http://vuejs.org/js/vue.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"> <my-component></my-component> <br> <button id="external-button">External Button</button> </div> <template id="my-template"> <div style="border: 1px solid; padding: 5px;"> <p>A counter: {{ count }}</p> <button @click="increaseCount">Internal Button</button> </div> </template>

因此,当我单击内部按钮时,increecount()方法被绑定到它的click事件,因此它被调用。没有办法将事件绑定到外部按钮,我正在用jQuery监听其单击事件,所以我需要其他方法来调用增加量计数。

EDIT

这似乎是可行的:

vm.$children[0].increaseCount();

然而,这不是一个好的解决方案,因为我是通过它在子数组中的索引来引用组件的,对于许多组件来说,这不太可能保持不变,代码的可读性也较差。


当前回答

在组件中像这样声明你的函数:

export default {
  mounted () {
    this.$root.$on('component1', () => {
      // do your logic here :D
    });
  }
};

并像这样从任何页面调用它:

this.$root.$emit("component1");

其他回答

在组件中像这样声明你的函数:

export default {
  mounted () {
    this.$root.$on('component1', () => {
      // do your logic here :D
    });
  }
};

并像这样从任何页面调用它:

this.$root.$emit("component1");

如果你使用Vue 3和<script setup> sugar,请注意,组件的内部绑定是关闭的(从组件外部不可见),你必须使用defineExpose(参见docs)使它们从外部可见。就像这样:

<script setup lang="ts">
const method1 = () => { ... };
const method2 = () => { ... };

defineExpose({
  method1,
  method2,
});
</script>

默认情况下关闭正在使用的组件

我使用了一个非常简单的解决方案。我已经包括了一个HTML元素,调用方法,在我的Vue组件,我选择,使用香草JS,我触发点击!

在Vue组件中,我包含了如下内容:

<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>

我使用香草JS:

const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();                

假设你在子组件中有一个child_method():

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}

现在你想从父组件执行child_method:

<template>
    <div>
        <button @click="exec">Execute child component</button>
        <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
    </div>
</template>

export default {
    methods: {
        exec () { //accessing the child component instance through $refs
            this.$refs.child.child_method() //execute the method belongs to the child component
        }
    }
}

如果你想从子组件执行父组件方法:

parent.name_of_method美元。()

注意:不建议像这样访问子组件和父组件。

相反,作为最佳实践,使用道具和事件进行亲子交流。

如果你想要组件之间的通信,一定要使用vuex或事件总线

请阅读这篇非常有用的文章


这里有一个简单的例子

this.$children[indexOfComponent].childsMethodName();