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>
相关推荐
Jagger_37 分钟前
周末和AI肝了两天,终于知道:为什么要把AI当做实习生
前端
weixin_4561648339 分钟前
vue3 子组件向父组件传参
前端·vue.js
沉鱼.4443 分钟前
第十二届题目
java·前端·算法
Setsuna_F_Seiei1 小时前
CocosCreator 游戏开发 - 多维度状态机架构设计与实现
前端·cocos creator·游戏开发
Bigger1 小时前
CodeWalkers:让 AI 助手化身桌面宠物,陪你敲代码的赛博伙伴!
前端·app·ai编程
cyclv2 小时前
无网络地图展示轨迹,地图瓦片下载,绘制管线
前端·javascript
土豆12503 小时前
Tauri 入门与实践:用 Rust 构建你的下一个桌面应用
前端·rust
惜茶3 小时前
vue+SpringBoot(前后端交互)
java·vue.js·spring boot
小陈工4 小时前
2026年4月2日技术资讯洞察:数据库融合革命、端侧AI突破与脑机接口产业化
开发语言·前端·数据库·人工智能·python·安全
IT_陈寒5 小时前
Vue的这个响应式问题,坑了我整整两小时
前端·人工智能·后端