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

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


当前回答

有时您希望将这些内容包含在组件中。根据DOM状态(当Vue组件实例化时,监听的元素必须存在于DOM中),您可以从Vue组件内部监听组件外部元素上的事件。假设在组件外部有一个元素,当用户单击它时,您希望组件做出响应。

在html中,你有:

<a href="#" id="outsideLink">Launch the component</a>
...
<my-component></my-component>

在你的Vue组件中:

    methods() {
      doSomething() {
        // do something
      }
    },
    created() {
       document.getElementById('outsideLink').addEventListener('click', evt => 
       {
          this.doSomething();
       });
    }
    

其他回答

我使用了一个非常简单的解决方案。我已经包括了一个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();                

您可以使用Vue事件系统

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

and

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

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

对于Vue2,这适用于:

var bus = new Vue()

//组件A的方法

bus.$emit('id-selected', 1)

//组件B创建的钩子

bus.$on('id-selected', function (id) {

  // ...
})

在这里查看Vue文档。 这里详细介绍了如何设置这个事件总线。

如果您想了解何时使用属性、事件和/或集中状态管理的更多信息,请参阅本文。

请看下面托马斯关于Vue 3的评论。

这是一种从其他组件访问一个组件的方法的简单方法

// This is external shared (reusable) component, so you can call its methods from other components

export default {
   name: 'SharedBase',
   methods: {
      fetchLocalData: function(module, page){
          // .....fetches some data
          return { jsonData }
      }
   }
}

// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];

export default {
   name: 'History',
   created: function(){
       this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
   }
}

一个稍微不同(更简单)的公认答案:

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

export default {
    components: { 'my-component': myComponent }
}

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

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

访问组件方法:

<script>
    this.$refs.foo.doSomething();
</script>