【Vue基础】父子组件之间的数据传递

父组件向子组件传递数据

父组件要做的:

1.父组件import引用子组件;

2.在components中注册子组件;

3.通过v-bind属性向子组件中传值。

例如:

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

子组件要做的:

4.子组件通过props获取父组件传递的值;

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

子组件向父组件传递数据

1.子组件中通过子组件的$emit方法自定义事件向父组件传数据

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

2.父组件通过监听子组件自定义的事件获取子组件传的值

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

父组件通过调用getChildMsg函数来处理监听到的值。

猜你喜欢

转载自blog.csdn.net/DrLemonPie/article/details/123924615