Javascript 从组件外部调用 Vue.js 组件方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33682651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a Vue.js component method from outside the component
提问by harryg
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?
假设我有一个包含子组件的主 Vue 实例。有没有办法完全从 Vue 实例外部调用属于这些组件之一的方法?
Here is an example:
下面是一个例子:
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>
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
.
因此,当我单击内部按钮时,该increaseCount()
方法将绑定到其单击事件,因此它会被调用。无法将事件绑定到外部按钮,我正在使用 jQuery 侦听其单击事件,因此我需要其他一些方法来调用increaseCount
.
EDIT
编辑
It seems this works:
这似乎有效:
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.
但是,这不是一个好的解决方案,因为我通过其在 children 数组中的索引来引用组件,并且对于许多组件,这不太可能保持不变,并且代码可读性较差。
回答by harryg
In the end I opted for using Vue's ref
directive. This allows a component to be referenced from the parent for direct access.
最后我选择使用Vue 的ref
指令。这允许从父级引用组件以进行直接访问。
E.g.
例如
Have a compenent registered on my parent instance:
在我的父实例上注册了一个组件:
var vm = new Vue({
el: '#app',
components: { 'my-component': myComponent }
});
Render the component in template/html with a reference:
使用引用在模板/html 中呈现组件:
<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>
See this fiddle for an example: https://jsfiddle.net/xmqgnbu3/1/
以这个小提琴为例:https: //jsfiddle.net/xmqgnbu3/1/
(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)
(使用 Vue 1 的旧示例:https: //jsfiddle.net/6v7y6msr/)
回答by musicformellons
Since Vue2 this applies:
由于 Vue2 这适用:
var bus = new Vue()
// in component A's method
// 在组件 A 的方法中
bus.$emit('id-selected', 1)
// in component B's created hook
// 在组件 B 的创建钩子中
bus.$on('id-selected', function (id) {
// ...
})
See herefor the Vue docs. And hereis more detail on how to set up this event bus exactly.
有关Vue 文档,请参见此处。而在这里是如何设置这个事件总线准确详细。
If you'd like more info on when to use properties, events and/ or centralized state management see this article.
如果您想了解有关何时使用属性、事件和/或集中状态管理的更多信息,请参阅这篇文章。
回答by Helder Lucas
You can use Vue event system
你可以使用Vue事件系统
vm.$broadcast('event-name', args)
and
和
vm.$on('event-name', function())
Here is the fiddle: http://jsfiddle.net/hfalucas/wc1gg5v4/59/
回答by Victor
A slightly different (simpler) version of the accepted answer:
已接受答案的略有不同(更简单)的版本:
Have a component registered on the parent instance:
在父实例上注册一个组件:
export default {
components: { 'my-component': myComponent }
}
Render the component in template/html with a reference:
使用引用在模板/html 中呈现组件:
<my-component ref="foo"></my-component>
Access the component method:
访问组件方法:
<script>
this.$refs.foo.doSomething();
</script>
回答by Cong Nguyen
You can set ref for child components then in parent can call via $refs:
您可以为子组件设置 ref,然后在父组件中可以通过 $refs 调用:
Add ref to child component:
将 ref 添加到子组件:
<my-component ref="childref"></my-component>
Add click event to parent:
将点击事件添加到父级:
<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>
回答by roli roli
Say you have a child_method()
in the child component:
假设您child_method()
在子组件中有一个:
export default {
methods: {
child_method () {
console.log('I got clicked')
}
}
}
Now you want to execute the child_method
from parent component:
现在要执行child_method
from 父组件:
<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
}
}
}
If you want to execute a parent component method from child component:
如果要从子组件执行父组件方法:
this.$parent.name_of_method()
this.$parent.name_of_method()
NOTE: It is not recommended to access the child and parent component like this.
注意:不建议像这样访问子组件和父组件。
Instead as best practice use Props & Events for parent-child communication.
相反,作为最佳实践,使用 Props & Events 进行亲子交流。
If you want communication between components surely use vuexor event bus
Please read this very helpful article
请阅读这篇非常有用的文章
回答by Dotnetgang
This is a simple way to access a component's methods from other component
这是从其他组件访问组件方法的简单方法
// 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');
}
}
回答by Rohit Kumar
I am not sure is it the right way but this one works for me.
First import the component which contains the method you want to call in your component
我不确定这是不是正确的方法,但这个方法对我有用。
首先导入包含要在组件中调用的方法的组件
import myComponent from './MyComponent'
and then call any method of MyCompenent
然后调用 MyCompenent 的任何方法
myComponent.methods.doSomething()
回答by Pratik Khadtale
Here is a simple one
这是一个简单的
this.$children[indexOfComponent].childsMethodName();
回答by Gorbas
I have used a very simple solution. I have included a HTML element, that calls the method, in my Vue Component that I select, using Vanilla JS, and I trigger click!
我使用了一个非常简单的解决方案。我使用 Vanilla JS 在我选择的 Vue 组件中包含了一个调用该方法的 HTML 元素,然后触发点击!
In the Vue Component, I have included something like the following:
在 Vue 组件中,我包含了如下内容:
<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>
That I use using Vanilla JS:
我使用 Vanilla JS:
const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();