• defineExpose ,父组件获取子组件中的属性值


    在这里插入图片描述

    <template>
      <div>
        <div>父组件div>
        <detail ref="sonRef">detail>
        <el-button @click="getSonMessage">获取子组件数据el-button>
        <div>{{ message }}div>
        <div v-for="item in state.fatherList " :key ="item.id">{{ item.name}}div>
      div>
    template>
    <script setup>
    import { ref,toRefs ,reactive} from "vue";
    import detail from "@/views/role/detail.vue";
    let sonRef = ref("sonRef");
    let message = ref("")
    let state=reactive({
      fatherList:[],
    })
    let getSonMessage=()=>{
      console.log(sonRef.value.sonInfo,sonRef.value.dataList,"+sonInfo")
      state.fatherList = sonRef.value.dataList
      message.value = sonRef.value.message
      sonRef.value.show()
    }
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    <template>
      <div>子组件div>
      <div v-for="item in state.dataList" :key="item.id">{{item.name}}子组件div>
    template>
    <script setup>
    import { defineExpose, onMounted, reactive, ref, toRefs } from "vue";
    import { getuserListApi } from "@/api/user";
    let message = ref("简单类型");
    let state = reactive({
      dataList: [{ id: 1, name: 123 }],
      sonInfo: {
        name: "子组件",
        tip: "对象",
      },
    });
    onMounted(async () => {
      let { code, data } = await getuserListApi();
      if (code == 0) {
        state.dataList = data;
      }
    });
    let show = () => {
      console.log("子组件的show方法");
    };
    let { dataList } = toRefs(state);
    
    defineExpose({
      //用state.dataList父组件接收的是初始化的数据,
      // 不是从onMounted里面取的数据,但是子组件的datalist是从onMounted拿到的最新数据。
      // 把dataList从state里面通过toRefs解构,父组件也可拿到最新的数据
      dataList: dataList,
      message,
      show,
      sonInfo: state.sonInfo,
    });
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    任务系统之API子任务
    编码技巧 --- 使用dynamic简化反射
    iqoo的“牛皮”还能吹多大?
    MyBatis开发的详细步骤
    从云AK泄露利用看企业特权管理
    【云原生之K8S】k8s资源限制以及探针检查
    openfoam并行通信探索(一)
    7.JSP
    React知识点系列(2)-每天10个小知识
    微信小程序canvas2d使用封装与案例使用
  • 原文地址:https://blog.csdn.net/qq_42859450/article/details/125894360