Vue父子组件通信

数据传递

父组件 => 子组件

父组件传递

<Child
  hobby="唱,跳,RAP"
  :age=“age”
/>

子组件接收

props: {
  hobby: {
    type: String,
    default: ''
  },
  age: {
	type: Number,
    default: 2.5
  }
}

子组件 => 父组件

子组件通过调用父组件的方法,以参数的方式传递到父组件

<Child
  :play="play"
/>
play(sth) {
  console.log(`今天去${sth}`);
}

方法调用

子组件调用父组件方法
  • 通过props将方法传递到子组件
props: {
  play: {
    type: Function,
    default: () => {}
  }
}
<div>
   <span>{{hobby}}</span>
   <button @click="play('RAP')">玩去</button>
 </div>
  • this.$parent
  • this.$emit()
父组件调用子组件方法
  • 设置ref
<Child
 ref="child"
/>
<button @click="doSth">去玩</button>
doSth() {
 this.$refs.child.callMeDo('写作业');
}
  • 在子组件创建成功后,将this传递给父组件
    父组件
<Child
 :onRef="onRef"
/>
<button @click="doSth">去玩</button>
onRef(child) {
 this.child = child;
}

子组件

props: {
 onRef: {
   type: Function,
   default: () => {}
 }default: () => {}
 }
}
created(){
 this.onRef(this);
}

总结:

  • 父组件的数据和方法都可以通过props的方式传递到子组件,子组件在接收父组件的数据或方法时应进行验证。
  • 子组件也可以通过this.$parent得到父组件的,再去获取父组件的数据,调用父组件的方法。
  • 父组件可以通过设置ref的方式获取子组件的实例,进而拿到子组件的数据,调用子组件的方法。
  • 设置ref还可以在子组件的created()生命周期内,将this通过函数的方式传递给父组件。

相关源代码:
父组件

<template>
  <div>
    <Child
      :onRef="onRef"
      :play="play"
      hobby="唱,跳,RAP"
      ref="child1"
    />
    <button @click="doSth">去玩</button>
  </div>
</template>

<script>
import Child from './Child'
export default {
  name: "Parent",
  components: {
    Child
  },
  methods: {
    onRef(child) {
      this.child2 = child;
    },
    play(sth) {
      console.log(`今天去${sth}`);
    },
    doSth() {
      this.$refs.child1.callMeDo('写作业');
      this.child2.callMeDo('吃饭');
    }
  }
}
</script>

<style lang="less">

</style>

子组件

<template>
  <div>
    <span>{{hobby}}</span>
    <button @click="play('RAP')">玩去</button>
  </div>
</template>

<script>
export default {
  name: "Child",
  props: {
    hobby: {
      type: String,
      default: ''
    },
    onRef: {
      type: Function,
      default: () => {}
    },
    play: {
      type: Function,
      default: () => {}
    }
  },
  created(){
    this.onRef(this);
  },
  methods: {
    callMeDo(sth) {
      console.log(`父组件让做的事${sth}`);
    }
  }
}
</script>

<style lang="less">

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值