Preface
The method of the parent component of vue3 calls the child component is throughexpose
andref
To achieve it, we canexpose
To control the methods and objects that the parent component can access to the child component, we will usesetup api
(combination API) andoption api
(optional api) to demonstrate how the parent component calls the child component's methods.
1. Combination API
The parent component defines a child component instance through ref, and obtains the data and methods of the child component by calling the instance.
<!-- Parent component --> <template> <div class="itxst"> <!-- use ref Directive association subcomponents --> <child ref="childComp"/> <button @click="onTry">Click to give it a try</button> </div> </template> <script setup> import { reactive, ref } from "vue"; import child from "./"; //Define the subcomponent instance, the name should be the same as the above refconst childComp = ref(null); //A method or object to access demo componentconst onTry = () => { //Get title data of the child component let msg = ; //Calling the play method of the child component (); }; </script>
Subcomponents expose objects and methods through defineExpose
<!--Subcomponent name --> <template> <div class="itxst"> {{ }} </div> </template> <script setup> import { ref, reactive } from "vue"; //Define a variableconst state = reactive({ title: "", }); //Define a methodconst play = () => { = "You called the method of the child component"; }; //Expose state and play methodsdefineExpose({ state, play, }); </script>
2. Optional API
<!-- Parent component --> <template> <div class="itxst"> <!-- use ref Order --> <child ref="childComp"/> <button @click="onClick">Click to give it a try</button> </div> </template> <script > import child from "./"; export default { name: "app", //Register component components: { child, }, methods: { onClick: function () { //Get the data of the subcomponent let msg = this.$; //Execute the play method of the child component this.$(); }, }, }; </script>
<!-- Subcomponents --> <template> <div class="itxst"> {{ title }} </div> </template> <script> //The default current instance is exposedexport default { name: "demo", //Default exposure is all. You can also control those that need to be exposed through expose. //expose: ['play'], data() { return { title: "", }; }, methods: { play: function () { = "You called the method of the child component"; }, }, }; </script>
Summarize
This is the end of this article about vue3 parent component calling child components. For more related content of vue3 parent component calling child components, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!