父组件用ref获取子组件数据

在这里插入图片描述在这里插入图片描述

子组件
Son/index.vue

子组件的数据和方法一定要记得用defineExpose暴露,不然父组件用ref是获取不到的!!!

<script setup>
import { ref } from "vue";
const sonNum = ref(1);
const changeSon = () => {
  sonNum.value++;
};

defineExpose({
  sonNum,
  changeSon,
});
</script>

<template>
  <div class="son">
    {{ sonNum }}
  </div>
</template>

<style scoped lang="scss">
.son {
  width: 100px;
  height: 20px;
  border: 1px pink solid;
}
</style>

Father/index.vue

<script setup>
import { ref, onMounted, watch, computed } from "vue";

import Son from "../Son/index.vue";
const SonRef = ref(null);
let father = ref();
let sonNumInFather = ref(null);
// console.log("SonRef.value", SonRef.value);
onMounted(() => {
  father.value = SonRef.value.sonNum;
  console.log("SonRef.value", SonRef.value.sonNum);
  console.log("SonRef.value", SonRef.value.changeSon);

  //   sonNumInFather.value = SonRef.value.sonNum;这样写也可以,但是不会是响应式数据,就永远是初始化的1,不会因为点击按钮就++

  //   用watch可以实现sonNumInFather是响应数据
  //   watch(
  //     () => SonRef.value.sonNum,
  //     () => {
  //       father.value = SonRef.value.sonNum;
  //       console.log("hhhhh");
  //     }
  //   );
  //  用computed可以实现sonNumInFather是响应数据
  sonNumInFather.value = computed(() => {
    return SonRef.value.sonNum;
  });
});

const FatherChangeSon = () => {
  SonRef.value.changeSon();
};
</script>

<template>
  <button @click="FatherChangeSon">son+1</button>
  <Son ref="SonRef"></Son>
  {{ sonNumInFather }}
  <!-- 下面这两个都渲染不成功,都不行 -->
  <!-- {{ SonRef.sonNum }} -->
  <!-- {{ father }} -->
  // 很奇怪这样就可以了,可以正常显示,也不报错
  {{ SonRef?.sonNum }}
</template>

<style scoped lang="scss"></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值