从组件外部调用 Vue.js 组件方法

新手上路,请多包涵

假设我有一个包含子组件的主 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>

所以当我点击内部按钮时, increaseCount() 方法被绑定到它的点击事件,所以它被调用。无法将事件绑定到外部按钮,我正在使用 jQuery 监听其单击事件,因此我需要一些其他方法来调用 increaseCount

编辑

似乎这有效:

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

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

原文由 harryg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 679
2 个回答

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

例如

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

 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/xmqgnbu3/1/

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

为 Vue3 编辑 - 组合 API

子组件必须在 setupreturn 要在父组件中使用的函数,否则该函数对父组件不可用。

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

原文由 harryg 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以为子组件设置 ref,然后在父组件中可以通过 $refs 调用:

将 ref 添加到子组件:

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

给父级添加点击事件:

 <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>

 var vm = new Vue({
  el: '#app',
  components: {
    'my-component': {
      template: '#my-template',
      data: function() {
        return {
          count: 1,
        };
      },
      methods: {
        increaseCount: function() {
          this.count++;
        }
      }
    },
  }
});
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <my-component ref="childref"></my-component>
  <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
</div>

<template id="my-template">
  <div style="border: 1px solid; padding: 2px;" ref="childref">
    <p>A counter: {{ count }}</p>
    <button @click="increaseCount">Internal Button</button>
  </div>
</template>

原文由 Cong Nguyen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题