[Vue Basics] Data transfer between parent and child components

Pass data from parent component to child component

What the parent component does:

1. The parent component import refers to the child component;

2. Register subcomponents in components;

3. Pass the value to the child component through the v-bind attribute.

For example:

<child :parent-name="parentName"></child>

What the subcomponents do:

4. The child component obtains the value passed by the parent component through props;

props: {
    
     /* 通过属性接收父组件传过来的数据,属性是parent-fun, props中可以使用parentFun变量接收 */ 
  parentName: {
    
    
    type: String,
    default: () => '',
  },
}

Pass data from child component to parent component

1. In the child component, the $emit method of the child component is used to customize the event to pass data to the parent component

methods: {
    
    
  sendMsgToParent() {
    
     //1.子组件通过子定义事件child-msg的方式将msg传给父组件
    this.$emit('child-msg', this.msg)
  }
}

2. The parent component obtains the value passed by the child component by listening to the custom event of the child component

<child @child-msg="getChildMsg" :parent-name="parentName"></child>

The parent component processes the listened value by calling the getChildMsg function.

Guess you like

Origin blog.csdn.net/DrLemonPie/article/details/123924615