There are several ways to implement the parent component triggers the method in the child component, and the following are two commonly used methods:
1 Get the child component instance through ref and call the method
The parent component can name the child component through ref in the template, and then use $refs in the parent component to access the child component instance.
<!-- Parent component --> <template> <div> <button @click="callChildMethod">Calling child component method</button> <child-component ref="child"></child-component> </div> </template> <script> import ChildComponent from './' export default { components: { ChildComponent }, methods: { callChildMethod() { this.$(); //Not passing the parameters this.$(param); //You can directly pass parameter param to subcomponent } } } </script>
In child components, the childMethod method to be called needs to be defined in methods.
<!-- Subcomponents --> <template> <div> <!-- Component content --> </div> </template> <script> export default { methods: { childMethod() { ('Subcomponent method is called') }, childMethodParam(param) { ('The child component method is called and the parameters passed by the parent component are received:',param) } } } </script>
2 Use custom events
The parent component can trigger a custom event through $emit when it needs to trigger a method in the child component. Then listen to the event in the child component and execute the corresponding method in the event callback function.
<!-- Parent component --> <template> <div> <button @click="callChildMethod">Calling child component method</button> <child-component @custom-event="onCustomEvent"></child-component> </div> </template> <script> import ChildComponent from './' export default { components: { ChildComponent }, methods: { callChildMethod() { this.$emit('custom-event') }, onCustomEvent() { ('custom-event event is fired') } } } </script>
In child components, you need to receive custom events passed by the parent component through props and listen to them during the created life cycle.
<!-- Subcomponents --> <template> <div> <!-- Component content --> </div> </template> <script> export default { props: ['customEvent'], created() { this.$on('custom-event', ) }, methods: { childMethod() { ('Subcomponent method is called') } } } </script>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.