Utilizing Vue 3 Composition API
To implement the Vue 3 Composition API, you can create a ref
for the child component within the template and access it using <ref>.value
to interact with the child component directly.
<script setup>
import {ref} from 'vue';
const childComponentRef = ref(null);
function activate() {
// Utilize `childComponentRef.value` to reach the component instance
childComponentRef.value.performAction(2.0);
}
</script>
<template>
<div>
<child-component ref="childComponentRef" />
<button @click="activate">Click here</button>
</div>
</template>
There are a few key points to keep in mind:
- If your child component is utilizing
<script setup>
, make sure to define public methods (such as performAction
in the example) using defineExpose
.
- In case of using Typescript, refer to details on how to annotate types here.
Vue 3 Options API / Vue 2 Approach
For the Vue 3 Options API or Vue 2, assign a ref
to the child component and utilize $refs
to call methods directly on the child component.
HTML snippet:
<div id="app">
<child-component ref="childComponent"></child-component>
<button @click="activate">Click Here</button>
</div>
Javascript implementation:
var ChildComponent = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
}
}
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
},
methods: {
activate: function() {
this.$refs.childComponent.setValue(2.0);
}
}
})
Refer to the Vue 3 documentation on component refs or the Vue 2 guide on refs for further information.