从组件外部调用Vue JS组件方法 [英] Call a Vue JS component method from outside the component

查看:127
本文介绍了从组件外部调用Vue JS组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含子组件的主Vue实例。有没有办法完全从Vue实例外部调用属于这些组件之一的方法?

Let's say I have a main Vue instance that has child components. Is there a way of calling a method belonging to one of these components from outside the Vue instance entirely?

这是一个例子:

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()方法绑定到其click事件,以便调用它。没有办法将事件绑定到外部按钮,我用jQuery监听其click事件,所以我还需要一些其他方法来调用 increaseCount

So when I click the internal button, the increaseCount() method is bound to its click event so it gets called. There is no way to bind the event to the external button, whose click event I am listening for with jQuery, so I'll need some other way to call increaseCount.

编辑

这似乎有效:

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

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

However, this is not a good solution because I am referencing the component by its index in the children array, and with many components this is unlikely to stay constant and the code is less readable.

推荐答案

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

In the end I opted for using Vue's ref directive. This allows a component to be referenced from the parent for direct access.

例如

在上面注册一个竞争对手我的父实例:

Have a compenent registered on my parent instance:

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

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

Render the component in template/html with a reference:

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

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

Now, elsewhere I can access the component externally

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

看一下这个小提琴的例子: https://jsfiddle.net/xmqgnbu3/1/

See this fiddle for an example: https://jsfiddle.net/xmqgnbu3/1/

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

(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)

这篇关于从组件外部调用Vue JS组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆