Search code examples
vue.jsvue-componentvuejs3

Vue 3 - Execute method from another component


A silly question but I am new to Vue js ...

Hello,

Is there any way to execute a method from another component?

for example I have 2 components

componentOne.vue

<template>
  <section>
          <div>Submit</div>
  </section>
</template>

<script>
export default {
  
};
</script>

componentTwo.vue

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

<script>
methods: {
    myMethod() {
      //some code
    },


</script>

I want to add a @click listener to the div element from componentOne and execute the method from component Two. Is it that possible somehow ?

I tried to use the $emit method but I think that this is the wrong way to make it work.


Solution

  • 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>