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

JavaScript

小胖凯前端

2020-03-09

假设我有一个具有子组件的主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()方法绑定到其click事件,因此将被调用。无法将事件绑定到外部按钮,我正在使用jQuery监听其单击事件,因此我需要其他一些调用方法increaseCount

编辑

看来这可行:

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

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

第326篇《从组件外部调用Vue.js组件方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
西门Sam 2020.03.09

这是一个简单的

this.$children[indexOfComponent].childsMethodName();

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android