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>
相关推荐
mucheni3 分钟前
迅为RK3568开发板OpeHarmony学习开发手册-修改应用程序名称
linux·前端·学习
WebGirl5 分钟前
SSE服务
前端
Mintopia11 分钟前
🛰️ 低带宽环境下的 AIGC 内容传输优化技术
前端·人工智能·trae
浮游本尊12 分钟前
Vue.js 项目静态资源 OSS 部署完整实现指南
vue.js
h***346316 分钟前
Nginx 缓存清理
android·前端·后端
Mintopia23 分钟前
⚡Trae Solo Coding 的效率法则
前端·人工智能·trae
wa的一声哭了33 分钟前
WeBASE管理平台部署-WeBASE-Web
linux·前端·网络·arm开发·spring boot·架构·区块链
孟陬33 分钟前
我的 starship 终端配置
前端
Moment35 分钟前
专为 LLM 设计的数据格式 TOON,可节省 60% Token
前端·javascript·后端
JarvanMo36 分钟前
Apple更新App审核条款,严打擅自与第三方 AI 共享个人数据的应用
前端