Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are different ways to invoke Vue3 component methods externally, depending on the use case and the relationship between the components.

One way is to use refs to obtain a reference to the target component instance and call its methods. For example, suppose a parent component has a child component that exposes a method called doSomething(). The parent component can create a ref for the child component and use it to call the method:

<template>
  <ChildComponent ref="childRef" />
  <button @click="invokeChildMethod">Invoke Child Method</button>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: { ChildComponent },
  methods: {
    invokeChildMethod() {
      this.$refs.childRef.doSomething()
    }
  }
}
</script>

Another way is to emit a custom event from the child component and listen to it in the parent component. For example, suppose the child component emits an event called do-something when its method is called:

<template>
  <button @click="doSomething">Do Something</button>
</template>

<script>
export default {
  methods: {
    doSomething() {
      this.$emit('do-something')
    }
  }
}
</script>

Then the parent component can listen to the event and invoke the child method:

<template>
  <ChildComponent @do-something="invokeChildMethod" />
  <button @click="invokeChildMethod">Invoke Child Method</button>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: { ChildComponent },
  methods: {
    invokeChildMethod() {
      this.$refs.childRef.doSomething()
    }
  }
}
</script>

Note that in both cases, the child component needs to expose its method either as a regular method or as an event listener. Also, it's important to consider the timing and context of the method invocation, as it may affect the state and behavior of the components.