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

查看:100
本文介绍了从组件外部调用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监听其单击事件,因此我将需要其他方法来调用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的ref指令.这样就可以从父级引用组件以进行直接访问.

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/

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

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

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

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