[Vuejs]-Vue 3 – Execute method from another component

0πŸ‘

βœ…

I would use the recommended way, props down, events up. E.g. you send an emit from componentOne which you catch in the parent and this is setting a prop on componentTwo which has a watch on this prop where you can execute the method.

parent.vue

<template>
  <componentOne @component-clicked="triggered = true"></componentOne>
  <componentTwo :triggered="triggered"></componentTwo>
</template>

<script setup>
const triggered = ref(false);
</script>

componentOne.vue

<template>
  <section>
          <div @click="emit('component-clicked')">Submit</div>
  </section>
</template>

<script setup>
const emit = defineEmits(['component-clicked']);
</script>

componentTwo.vue

<template>
  <section>
          <div>Lorem ipsum</div>
  </section>
</template>

<script setup>
const props = defineProps({
    triggered: { type: Boolean}
});
watch(
    () => props.triggered,
    () => {
        if (props.triggered === true) {
            //doStuff
        }
    }
);
</script>

0πŸ‘

you can do it this way if you want :

First, you need to register your components globally:

Register your components globally

Then in any component you can do :

import { getCurrentInstance } from 'vue';

const vm = getCurrentInstance();

vm?.appContext.app.component('MyComponent')?.call('MyMethod', ['myparameters']);

In your template :

<template>
  <Component1 @click="vm.appContext.app.component('Component2 ')?.call('MyMethod', ['myparameters'])"/>
  <Component2 />
</template>

0πŸ‘

I think you need a context to register componentTwo to componentOne, and then you can excute componentTwo’s method inside componentOne

-2πŸ‘

Do you want to do this without rendering the componentTwo? if yes, I am not sure if that is possible. If you are rendering the component you give it a ref, grab that ref in your script and call the method on that.

Leave a comment