Vue3.2+TS的defineExpose的应用

defineExpose通俗来讲,其实就是讲子组件的方法或者数据,暴露给父组件进行使用,这样对组件的封装使用,有很大的帮助,那么defineExpose应该如何使用,下面我来用一些实际的代码,带大家快速学会defineExpose的使用
1.子组件:子组件有方法increaseCount,和数据count,现在我们将这他们全部暴露出去。
ts 复制代码
<template>
  <div>
    <h1>子组件, 对defineExpose进行处理</h1>
    <button @click="increaseCount">Increase Count</button>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const count = ref(0)
const increaseCount = () => {
  count.value++;
};
defineExpose({
  count,
  increaseCount
})

</script>
<style scoped lang="less">
</style>
2.父组件:我们为子组件定义ref为childexpose,这里有一个问题,如果这样let childexpose = ref(null)声明,ts会提示"childexpose.value"可能为 "null"。所以直接let childexpose = ref(),ts就不会报错
在调用方法的时候,直接childexpose.value.increaseCount()就可以拿到他的方法,并且子组件的数据也会同步更新
ts 复制代码
<template>
  <div>
    <dExpose ref="childexpose"></dExpose>
    <a-button type="primary" status="warning" @click="getChild">Primary</a-button>
    {{nums}}
  </div>
</template>

<script setup lang="ts">
import { ref,onActivated  } from "vue";
import dExpose from './components/defineExpose.vue'

let nums = ref(null)
let childexpose = ref()

// 调用子组件的方法
const getChild = ()=>{
  childexpose.value.increaseCount()
  nums.value = childexpose.value.count  
}

</script>
<style scoped lang="less">
ul {
  list-style-type: none;
  li {
    height: 30px;
    line-height: 30px;
    background-color: aqua;
    margin-bottom: 10px;
  }
}
</style>
相关推荐
Dontla4 分钟前
(临时解决)Chrome调试避免跳入第三方源码(设置Blackbox Scripts、将目录添加到忽略列表、向忽略列表添加脚本)
前端·chrome
我的div丢了肿么办11 分钟前
js函数声明和函数表达式的理解
前端·javascript·vue.js
AAA阿giao14 分钟前
JavaScript 对象字面量与代理模式:用“胡巴送花”讲透面向对象与设计思想
javascript
云中雾丽14 分钟前
React.forwardRef 实战代码示例
前端
朝歌青年说15 分钟前
一个在多年的技术债项目中写出来的miniHMR热更新工具
前端
高台树色15 分钟前
终于记住Javascript垃圾回收机制
javascript
武天16 分钟前
一个项目有多个后端地址,每个后端地址的请求拦截器和响应拦截器都不一样,该怎么封装
vue.js
Moonbit17 分钟前
倒计时 2 天|Meetup 议题已公开,Copilot 月卡等你来拿!
前端·后端
Glink18 分钟前
现在开始将Github作为数据库
前端·算法·github
小仙女喂得猪18 分钟前
2025 跨平台方案KMP,Flutter,RN之间的一些对比
android·前端·kotlin