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>
相关推荐
ttod_qzstudio几秒前
TypeScript 中的 Record:从重构工厂函数说起
typescript·record
真上帝的左手17 分钟前
24. 前端-js框架-Electron
前端·javascript·electron
毛发浓密的女猴子22 分钟前
Git Pull 策略完全指南:Merge、Rebase、Fast-forward 深度对比
前端
夏小花花23 分钟前
<editor> 组件设置样式不生效问题
java·前端·vue.js·xss
PieroPC23 分钟前
用 nicegui 3.0 + sqlite3 做个简单博客
前端·后端
weixin_3077791324 分钟前
Jenkins Ioncions API 插件:现代化图标库在持续集成中的应用
java·运维·开发语言·前端·jenkins
兔子零102425 分钟前
零硬件交互:如何用纯前端把摄像头变成 4000 个粒子的魔法棒?
前端·算法
北辰alk25 分钟前
Vue Router 组件内路由钩子全解析
前端·vue.js
克喵的水银蛇28 分钟前
Flutter 弹性布局实战:Row/Column/Flex 核心用法与优化技巧
前端·javascript·typescript
verse_armour29 分钟前
东南大学云课堂导出PPT
javascript