How to call the method of parent component in Vue component
In Vue.js, component is the basic unit for building applications. During the communication process between components, sub-components often need to call methods of parent components to implement some functions. This article will introduce a method of calling parent component methods in Vue components and provide specific code examples.
Vue components can pass data from parent components to child components through props attributes. Similarly, Vue components can also pass data upward or call methods through events. A parent component can enable child components to call these methods by providing methods and passing them as props to the child component. Here is a specific example.
Suppose there is a parent component Parent and a child component Child, and there is a method parentMethod
in the parent component that needs to be called by the child component. This can be achieved through the following steps:
parentMethod
<template> <div> <p>{{ message }}</p> <Child :childMethod="parentMethod"></Child> </div> </template> <script> import Child from './Child.vue' export default { components: { Child }, data() { return { message: 'Hello from Parent' } }, methods: { parentMethod() { console.log('parentMethod called') // 在这里编写父组件的方法逻辑 // ... } } } </script>
$emit
method calls the parent component's method<template> <div> <button @click="callParentMethod">Call Parent Method</button> </div> </template> <script> export default { props: ['childMethod'], methods: { callParentMethod() { this.childMethod() } } } </script>
In this way, the child component can call the parent component's parentMethod
method by clicking the button. In the child component, define the corresponding property name through props
, and then in the child component, you can call the method in the parent component through this.childMethod()
.
It is worth noting that props in Vue components are one-way data flow, that is, child components receive data or methods through props and cannot directly modify the data of the parent component. If you need to modify the data of the parent component, you can do so through events.
Summary:
In the Vue component, you can pass the method as a prop to the child component, so that the child component can call the method of the parent component. This method can easily implement interaction and communication between components in Vue components when needed.
The above is how to call the parent component method in the Vue component, and specific code examples are provided. Hope this helps!
The above is the detailed content of How to call the method of parent component in Vue component. For more information, please follow other related articles on the PHP Chinese website!