假设我有一个主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();

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


当前回答

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

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

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

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

其他回答

我不确定这是正确的方法,但这个方法适合我。 首先导入包含您想在组件中调用的方法的组件

import myComponent from './MyComponent'

然后调用mycomponent的任何方法

myComponent.methods.doSomething()

使用Vue 3:

const app = createApp({})

// register an options object
app.component('my-component', {
  /* ... */
})

....

// retrieve a registered component
const MyComponent = app.component('my-component')

MyComponent.methods.greet();

https://v3.vuejs.org/api/application-api.html#component

您可以使用Vue事件系统

vm.$broadcast('event-name', args)

and

 vm.$on('event-name', function())

这是小提琴: http://jsfiddle.net/hfalucas/wc1gg5v4/59/

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

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

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

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

最后我选择使用Vue的ref指令。这允许从父组件中引用组件进行直接访问。

E.g.

在父实例上注册一个组件:

var vm = new Vue({
    el: '#app',
    components: { 'my-component': myComponent }
});

在template/html中使用引用渲染组件:

<my-component ref="foo"></my-component>

现在,在其他地方我可以从外部访问组件

<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>

请看这个小提琴的例子:https://jsfiddle.net/0zefx8o6/

(使用Vue 1的旧示例:https://jsfiddle.net/6v7y6msr/)

编辑Vue3 -组合API

子组件必须在设置中返回你想在父组件中使用的函数,否则该函数对父组件不可用。

注意:< script setup> doc不受影响,因为它默认为模板提供了所有的函数和变量。