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


228

假设我有一个具有子组件的主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();

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


1
如果您想尝试一下,我使用mxins添加了一个答案。我认为我更喜欢以这种方式设置应用程序。
奥马尔·坦蒂

Answers:


274

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

例如

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

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

使用引用渲染模板/ 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/


6
那是因为您可能尚未定义它。看链接的小提琴。
哈里格

29
如果您使用的是webpack,则vm由于其作用域模块的方式,您将无法访问。您可以window.app = vm在自己的计算机中执行类似操作main.js。资料来源:forum.vuejs.org/t/how-to-access-vue-from-chrome-console/3606
tw airball

1
可以认为这种方法是正常的吗?还是这是黑客?
CENT1PEDE

3
关于什么是hack与什么是“常规”编码有一个正式的定义,但是与其将这种方法称为hack(或者寻找实现同一目标的“ hacky”方式),不如问为什么需要这样做这个。在许多情况下,使用Vue的事件系统来触发外部组件行为,甚至问您为什么根本要在外部触发组件可能会更优雅。
哈里格

8
如果您尝试将视图组件集成到现有页面中,则会出现这种情况。与其完全重新设计页面,不如有时逐渐增加其他功能。
艾伦·王

37

从Vue2开始,这适用于:

var bus = new Vue()

//在组件A的方法中

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

//在组件B的已创建钩子中

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

  // ...
})

有关Vue文档,请参见此处。而在这里是如何设置这个事件总线准确详细。

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


1
简短而甜蜜!如果您不喜欢全局bus变量,则可以更进一步,并使用props将总线注入到组件中。我刚接触Vue,因此无法向您保证这是惯用的。
byxor


22

所接受答案的稍有不同(更简单)的版本:

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

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

使用引用渲染模板/ html中的组件:

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

访问组件方法:

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

21

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

将引用添加到子组件:

<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>


2
迄今为止最干净的解决方案。
grreeenn

好答案。我将编辑html,使其垂直方向变小。目前,我只能在运行“内部按钮”时看到它,这可能会造成混淆。
杰西·雷扎

8

假设您child_method()在子组件中有一个:

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}

现在,您要执行child_methodfrom父组件:

<template>
    <div>
        <button @click="exec">Execute child component</button>
        <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
    </div>
</template>

export default {
    methods: {
        exec () { //accessing the child component instance through $refs
            this.$refs.child.child_method() //execute the method belongs to the child component
        }
    }
}

如果要从子组件执行父组件方法:

this.$parent.name_of_method()

注意:不建议像这样访问子组件和父组件。

相反,作为最佳做法,请使用“道具和活动”进行亲子沟通。

如果您希望组件之间的通信一定要使用vuex事件总线

请阅读这篇非常有帮助的文章



是的,您可以但不被视为“最佳做法”:向下使用“儿童使用”属性,向上使用“父母使用”事件。为了涵盖“侧向”,请使用自定义事件,例如vuex。有关更多信息,请参见这篇不错的文章
musicformellons

是的,不建议这样做。
roli roli

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');
   }
}


1

我不确定这是正确的方法,但是这种方法对我有用。
首先导入包含您要在组件中调用的方法的组件

import myComponent from './MyComponent'

然后调用MyCompenent的任何方法

myComponent.methods.doSomething()

这不能让您访问组件中的任何数据。如果您 doSomething正在使用数据中的任何东西,则此方法无用。
cyboashu

-7

我使用了一个非常简单的解决方案。我使用Vanilla JS在我选择的Vue组件中包含了一个调用该方法的HTML元素,并且触发了点击!

在Vue组件中,我包括以下内容:

<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>

我使用Vanilla JS使用的代码:

const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();                

根本不认为这是好的做法,尤其是在OP的问题中。
混合式网络开发人员,
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.