SoFunction
Updated on 2025-04-07

Data transfer and method calls between parent and child components of Vue

In communication, whether the child component passes value to the parent component or the parent component to the child component, they all have one thing in common is that there is an intermediate medium. The child to the parent media is a custom event, and the parent to the child media is a property in props.

The parent component passes a value to the child component (Child components actively obtain the data and methods of the parent component)

Parent componentimportReference subcomponents
Add a subcomponent to the subcomponent when using a subcomponentv-bindproperty,And bind the data
Create in child components props ,existprops 中创建相同的property名,Used to receive data
把接收到的数据exist子组件中使用

The child component passes a value to the parent component (Parent component actively obtains data and methods of child components)

This custom event needs to be issued in the child component,Can be a click event for a button,It can be other ways
Put the value you want to pass $emit The position of the second parameter,This parameter will be passed to the response method in the parent component
Need to use child components in the parent component and bind listening to events on the child component label

Demo code:

// Parent component<template>
  <div >  
    <headerchild ref="headerChild"></headerchild>
    <button @click="getChild()">Parent component gets data and methods for child components</button>
  </div>
</template>
<script>
import HeaderChild from './HeaderChild'
export default {
  data () {
      return {
          title:'I am the data of the parent component'
      }
  },
  methods: {
     getChild (){
         (this.$)
     },
     run (){
         ("I am the method inside the parent component")
     }
  },
  components: {
      'headerchild': HeaderChild
  }
}
</script>
<style lang="sass" scoped>

</style>
//Subcomponent<template>
  <div >
      <button @click="getParent()">Get the data and methods of the parent component</button>
  </div>
</template>
<script>
export default {
  data () {
      return {
          name:'I am the data inside the child component'
      }
  },
  methods:{
      getParent(){
          (this.$) /*Get the entire parent component*/
          this.$()/*Methods to get parent component*/
      }
  },
  props:['title','run','home'] /*Receive data passed by the parent component through props */
}
</script>

This is the article about data transfer and method calls between Vue parent components and child components. For more relevant content on Vue parent components and child components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!