Call a Vue.Js Component Method from Outside the Component

Call a Vue.js component method from outside the component

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 component 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/0zefx8o6/

(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)

Edit for Vue3 - Composition API

The child-component has to return the function in setup you want to use in the parent-component otherwise the function is not available to the parent.

Note: <sript setup> doc is not affacted, because it provides all the functions and variables to the template by default.

Can't call Vue component method outside of it's element

I tested for a while.

  1. It might be not able to use @ in elements outside of Vue element
  2. The var viewModel seems not attached to window object

I can run with this though

JS

window.viewModel = new Vue({
el: "#app",
data: {},
methods: {
test: function() {
alert("test fuction called");
}
}
});

HTML

<div id="app">

</div>

<a onClick="viewModel.test()">Click me!</a>

vue.js - call component method from another component

yes it is possible. Step 3 will do what you explicitly asked but there are better ways.

Three ways.

1) VUEX: Move the method you wish to call, to Vuex and any associated reactive data properties to the store. And use getters to retrieve the updated data.

2) MIXINS: With mixins you would move your component2.vue and associated data properties to a mixin, and import it in both components, allowing it to be called from each.

3) Hacky fix that actually calls the method from another component (not best practice)

You can mount methods to $root and call them from another component, by emiting a event. Using your example it would look like the following.

Components2.vue // mount the method you wish to call


// new code
mounted() {

this.$root.$on("getProjects", () => {

return this.getProjects(url = '/api/departments');
});
}

Component1.vue // call the mounted method

 methods: {
// new code
emitGetProjects() {
this.$root.$emit("getProjects") //like this
}
},

more info here How can I call method in other component on vue.js 2? in case i made any typos

Calling a method inside Vue component from an outside class

Posting a better elaborated answer:
In vue.js you can use an Event Bus method to comunicate with unrelated components. Basically is a component that is used to pass an event to other components. It can be very useful in this case.

event-bus.js:

import Vue from 'vue';
export const EventBus = new Vue();

Component that will emit the event:

<template>
<div @click="functionToEmitTheEvent()"></div>
</template>

<script>
// Import the EventBus we just created.
import { EventBus } from './event-bus.js';

export default {
data() {
return {
clickCount: 0
}
},

methods: {
functionToEmitTheEvent() {
this.clickCount++;
// Send the event on a channel (customClick) with a payload (the click count.)
EventBus.$emit('customClick', this.clickCount);
}
}
}
</script>

Script that will listen the event:

// Import the EventBus.
import { EventBus } from './event-bus.js';

// Listen for the customClick event and its payload.
EventBus.$on('customClick', clickCount => {
console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`)
});

All code written was copied from here: https://alligator.io/vuejs/global-event-bus/

I hope it helped!

Vue parent component get response from child method

Your problem could be solved using refs and it works as follows:
In parent component:

 <parent @click="clickHandler">
<child ref="child" />
</parent>

In your parent script tag:

methods: {
async clickHandler(){
//call child component's method using reference given in parent component
await this.$refs.child.child_method_name();
// rest of your parent code here
}
}

How to access method from the child component in parent in Vue.js

Probably better to rethink the control flow, so that it have a clear separation of concern

  • A parent should not directly access child's method. If the method should be invoked via a button click, then the child can process the click and emit the event back to parent callabck handler. For details, check this

  • You may also check out state management, it can achieve what you want. Doc Link

Having said that, declaring a component in the parent and also include that component in parent's mixin doesn't seem common, and may not be a good practice.

Just a quick answer, there might be more way to achieve what you desire.

Vue2 call a method of other component

you can use the emit.

in the component A:

mounted() {
this.$root.$on("callMyMethod", () => {
this.myMethod();
});
},
methods: {
myMethod() {
// do something
},
},

and in the component B:

methods: {
doSomething() {
this.$root.$emit("callMyMethod");
},
},


Related Topics



Leave a reply



Submit