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>
相关推荐
【ql君】qlexcel14 分钟前
Notepad++ 复制宏、编辑宏的方法
开发语言·javascript·notepad++··宏编辑·宏复制
MiyueFE14 分钟前
14 个逻辑驱动的 UI 设计技巧,助您改善任何界面
前端·设计
啃火龙果的兔子18 分钟前
前端单元测试覆盖率工具有哪些,分别有什么优缺点
前端·单元测试
「、皓子~1 小时前
后台管理系统的诞生 - 利用AI 1天完成整个后台管理系统的微服务后端+前端
前端·人工智能·微服务·小程序·go·ai编程·ai写作
就改了1 小时前
Ajax——在OA系统提升性能的局部刷新
前端·javascript·ajax
凌冰_1 小时前
Ajax 入门
前端·javascript·ajax
京东零售技术1 小时前
京东小程序JS API仓颉改造实践
前端
奋飛1 小时前
TypeScript系列:第六篇 - 编写高质量的TS类型
javascript·typescript·ts·declare·.d.ts
老A技术联盟1 小时前
从小白入门,基于Cursor开发一个前端小程序之Cursor 编程实践与案例分析
前端·小程序
风铃喵游1 小时前
构建引擎: 打造小程序编译器
前端·小程序·架构