Method: 1. Call the method of the parent component through "this.$parent.event" in the child component. 2. The child component uses "$emit" to trigger an event to the parent component, and the parent component can listen to this event. 3. The parent component passes the method to the child component, and the method can be called directly in the child component.
The operating environment of this tutorial: Windows 7 system, vue version 2.9.6, DELL G3 computer.
In Vue, the sub-component calls the parent component. Here are three methods for reference.
The first method is directly in the sub-component. Call the method of the parent component through this.$parent.event
Parent component
<template> <p> <child></child> </p> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('测试'); } } }; </script>
Child component
<template> <p> <button @click="childMethod()">点击</button> </p> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } }; </script>
The second method is in the child Use $emit
in the component to trigger an event to the parent component, and the parent component can listen to this event.
Parent component
<template> <p> <child @fatherMethod="fatherMethod"></child> </p> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('测试'); } } }; </script>
Subcomponent
<template> <p> <button @click="childMethod()">点击</button> </p> </template> <script> export default { methods: { childMethod() { this.$emit('fatherMethod'); } } }; </script>
The third type is that the parent component passes the method into the subcomponent, in the subcomponent Call this method directly
parent component
<template> <p> <child :fatherMethod="fatherMethod"></child> </p> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('测试'); } } }; </script>
child component
<template> <p> <button @click="childMethod()">点击</button> </p> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { if (this.fatherMethod) { this.fatherMethod(); } } } }; </script>
[Related recommendations: vue.js tutorial]
The above is the detailed content of How does a vue subcomponent call the method of the parent component?. For more information, please follow other related articles on the PHP Chinese website!