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?
Here is an example:
var vm = new Vue({_x000D_
el: '#app',_x000D_
components: {_x000D_
'my-component': { _x000D_
template: '#my-template',_x000D_
data: function() {_x000D_
return {_x000D_
count: 1,_x000D_
};_x000D_
},_x000D_
methods: {_x000D_
increaseCount: function() {_x000D_
this.count++;_x000D_
}_x000D_
}_x000D_
},_x000D_
}_x000D_
});_x000D_
_x000D_
$('#external-button').click(function()_x000D_
{_x000D_
vm['my-component'].increaseCount(); // This doesn't work_x000D_
});
_x000D_
<script src="http://vuejs.org/js/vue.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="app">_x000D_
_x000D_
<my-component></my-component>_x000D_
<br>_x000D_
<button id="external-button">External Button</button>_x000D_
</div>_x000D_
_x000D_
<template id="my-template">_x000D_
<div style="border: 1px solid; padding: 5px;">_x000D_
<p>A counter: {{ count }}</p>_x000D_
<button @click="increaseCount">Internal Button</button>_x000D_
</div>_x000D_
</template>
_x000D_
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
.
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.
This question is related to
javascript
vue.js
In the end I opted for using Vue's ref
directive. This allows a component to be referenced from the parent for direct access.
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:
<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/
(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)