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>
相关推荐
Java展博4 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户112936112194 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼5 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_4195 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真6 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li7 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写8 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
RuoyiOffice8 小时前
Flowable只是起点:一套OA背后的单据、资源与协作设计
java·vue.js·spring boot·flowable·企业管理·oa·ruoyi office
TDengine (老段)8 小时前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
goehou10 小时前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp