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>
相关推荐
candyTong2 小时前
一觉醒来,大模型就帮我排查完页面性能问题
前端·javascript·架构
魔术师Grace2 小时前
我给 AI 做了场入职培训
前端·程序员
玩嵌入式的菜鸡3 小时前
网页访问单片机设备---基于mqtt
前端·javascript·css
前端一小卒3 小时前
我用 Claude Code 的 Superpowers 技能链写了个服务,部署前差点把服务器搞炸
前端·javascript·后端
深海鱼在掘金3 小时前
深入浅出 LangChain —— 第二章:环境搭建与快速上手
人工智能·typescript·langchain
滑雪的企鹅.4 小时前
HTML头部元信息避坑指南大纲
前端·html
一拳不是超人4 小时前
老婆天天吵吵要买塔罗牌,我直接用 AI 2 小时写了个在线塔罗牌
前端·ai编程
阿丰资源6 小时前
SpringBoot+Vue实战:打造企业级在线文档管理系统
vue.js·spring boot·后端
excel6 小时前
如何解决 Nuxt DevTools 中关于 unstorage 包的报错
前端
Rust研习社6 小时前
使用 Axum 构建高性能异步 Web 服务
开发语言·前端·网络·后端·http·rust