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>
相关推荐
去哪儿技术沙龙2 分钟前
去哪儿网前端代码自动生成技术实践
前端·ai编程
yyf198905257 分钟前
Vue 3的中文文献
typescript
前端九哥15 分钟前
装个依赖把公司电脑干报废了?npm i 到底背着我干了啥?
前端·javascript
溪海莘21 分钟前
React入门:跟读官方快速入门教程(前端小白)
前端·react.js·前端框架
绝世唐门三哥40 分钟前
工具函数-精准判断美东交易时间
前端·javascript·vue.js
Moment1 小时前
如何一次性生成 60 种语气表达?RWKV 模型告诉你答案 ❗❗❗
前端·后端·aigc
踢球的打工仔1 小时前
typescript-null和undefined
前端·javascript·typescript
前端小蜗1 小时前
对不起,我很贱:老板还没催,我自己就统计《GitLab年度代码报告》
前端·javascript·人工智能
佛系打工仔1 小时前
绘制K线第三章:拖拽功能实现
android·前端·ios
cauyyl1 小时前
react 项目检查国际化配置脚本
前端·react.js·前端框架