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

har*_*ryg 180 javascript vue.js

假设我有一个包含子组件的主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
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

因此,当我单击内部按钮时,该increaseCount()方法将绑定到其click事件,以便调用它.没有办法将事件绑定到外部按钮,我用jQuery监听其click事件,所以我还需要一些其他方法来调用increaseCount.

编辑

看来这很有效:

vm.$children[0].increaseCount();
Run Code Online (Sandbox Code Playgroud)

但是,这不是一个好的解决方案,因为我通过子数组中的索引引用组件,并且对于许多组件,这不太可能保持不变并且代码可读性较差.

har*_*ryg 231

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

例如

在我的父实例上注册了一个compnent:

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

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

<my-component ref="foo"></my-component>
Run Code Online (Sandbox Code Playgroud)

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

<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如果您正在使用webpack,那么由于它的范围模块,您将无法访问`vm`.您可以在`main.js`中执行类似`window.app = vm`的操作.资料来源:https://forum.vuejs.org/t/how-to-access-vue-from-chrome-console/3606 (26认同)
  • 如果您尝试将视图组件集成到现有页面中,则会出现这种情况.而不是完全重新设计页面,有时增量添加其他功能是很好的. (8认同)
  • 那是因为你可能还没有定义它.看看链接的小提琴. (6认同)
  • 我不得不使用这个。: this.$refs.foo.doSomething(); (5认同)
  • 对于什么是黑客与什么是"正常"编码有官方定义,但不是把这种方法称为黑客(或者寻找一种"不那么黑客"的方式来实现同样的事情),可能更好地质疑为什么你需要这样做这个.在许多情况下,使用Vue的事件系统触发外部组件行为可能更为优雅,甚至可能会问为什么要在外部触发组件. (3认同)

Hel*_*cas 30

您可以使用Vue事件系统

vm.$broadcast('event-name', args)
Run Code Online (Sandbox Code Playgroud)

 vm.$on('event-name', function())
Run Code Online (Sandbox Code Playgroud)

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

  • @GusDeCooL示例已被编辑.并不是说在Vuejs 2.0之后使用的一些方法已被弃用 (4认同)

mus*_*ons 27

由于Vue2适用于:

var bus = new Vue()
Run Code Online (Sandbox Code Playgroud)

//在组件A的方法中

bus.$emit('id-selected', 1)
Run Code Online (Sandbox Code Playgroud)

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

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

  // ...
})
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解Vue文档.而在这里是如何设置这个事件总线准确详细.

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


Con*_*yen 11

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

将引用添加到子组件:

<my-component ref="childref"></my-component>
Run Code Online (Sandbox Code Playgroud)

将点击事件添加到父项:

<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
Run Code Online (Sandbox Code Playgroud)

<my-component ref="childref"></my-component>
Run Code Online (Sandbox Code Playgroud)
<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
Run Code Online (Sandbox Code Playgroud)

  • 迄今为止最干净的解决方案。 (2认同)

Vic*_*tor 11

A slightly different (simpler) version of the accepted answer:

Have a component registered on the parent instance:

export default {
    components: { 'my-component': myComponent }
}
Run Code Online (Sandbox Code Playgroud)

Render the component in template/html with a reference:

<my-component ref="foo"></my-component>
Run Code Online (Sandbox Code Playgroud)

Access the component method:

<script>
    this.$refs.foo.doSomething();
</script>
Run Code Online (Sandbox Code Playgroud)


dot*_*NET 6

如果您使用带有<script setup>Sugar 的 Vue 3,请注意组件的内部绑定是封闭的(从组件外部不可见),并且您必须使用defineExpose(请参阅文档)使它们从外部可见。像这样的东西:

<script setup lang="ts">
const method1 = () => { ... };
const method2 = () => { ... };

defineExpose({
  method1,
  method2,
});
</script>
Run Code Online (Sandbox Code Playgroud)

自从

使用的组件默认<script setup>关闭


rol*_*oli 5

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

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您要执行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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

this.$parent.name_of_method()

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

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

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

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



小智 5

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

// 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');
   }
}
Run Code Online (Sandbox Code Playgroud)