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>
相关推荐
Vic1010120 分钟前
解决 Spring Security 在异步线程中用户信息丢失的问题
java·前端·spring
源码获取_wx:Fegn089532 分钟前
基于springboot + vue二手交易管理系统
java·vue.js·spring boot·后端·spring·课程设计
wordbaby34 分钟前
Expo (React Native) 最佳实践:TanStack Query 深度集成指南
前端·react native
~无忧花开~1 小时前
Vue二级弹窗关闭错误解决指南
开发语言·前端·javascript·vue.js
软件技术NINI1 小时前
前端面试题:请描述一下你对盒模型的理解
前端
老华带你飞1 小时前
在线教育|基于springboot + vue在线教育系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
码事漫谈1 小时前
VS Code终端从入门到精通完全指南
前端·后端
wordbaby1 小时前
Expo (React Native) 本地存储全攻略:普通数据与敏感数据该存哪?
前端·react native
知行力1 小时前
【GitHub每日速递 20251209】Next.js融合AI,让draw.io图表创建、修改、可视化全靠自然语言!
javascript·人工智能·github
REDcker1 小时前
JS 与 C++ 语言绑定技术详解
开发语言·javascript·c++