Home > Article > Web Front-end > How to call the method of child component in vue parent component
Calling method: 1. In the parent component, directly call the child component's method through ref; 2. In the parent component, call through the component's "$emit" and "$on" methods.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
How to directly call the child component in the parent component in the Vue project:
Option 1: Directly call the child through ref Component method;
//父组件中 <template> <div> <Button @click="handleClick">点击调用子组件方法</Button> <Child ref="child"/> </div> </template> <script> import Child from './child'; export default { methods: { handleClick() { this.$refs.child.sing(); }, }, } </script> //子组件中 <template> <div>我是子组件</div> </template> <script> export default { methods: { sing() { console.log('我是子组件的方法'); }, }, }; </script>
Option 2: Through the $emit and $on methods of the component;
//父组件中 <template> <div> <Button @click="handleClick">点击调用子组件方法</Button> <Child ref="child"/> </div> </template> <script> import Child from './child'; export default { methods: { handleClick() { this.$refs.child.$emit("childmethod") //子组件$on中的名字 }, }, } </script> //子组件中 <template> <div>我是子组件</div> </template> <script> export default { mounted() { this.$nextTick(function() { this.$on('childmethods', function() { console.log('我是子组件方法'); }); }); }, }; </script>
Related recommendations: "vue.js Tutorial》
The above is the detailed content of How to call the method of child component in vue parent component. For more information, please follow other related articles on the PHP Chinese website!