Vue3中的defineExpose的认识

defineExpose

使用 <script setup> 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,** 不会 **暴露任何在 <script setup> 中声明的绑定。
可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性:

<script setup>
import {
    
     ref } from 'vue'

const a = 1
const b = ref(2)

defineExpose({
    
    
  a,
  b
})
</script>

demo案例:
写一个子组件,里面有一个message和add方法,然后再父组件中展示message和调用add的方法,代码如下:

子组件

<template>
<div class='content'>
 <h1>{
    
    {
    
    count}}</h1>
</div>
</template>

<script setup >
import {
    
     ref } from 'vue'
 const count = ref(0)
 const message = ref('Hello from Child!')
 const add = () => {
    
    
   count.value++
 }
 defineExpose({
    
    
   message,
   add
 })
</script>

父组件:

<template>
  <div class='content'>
    <h1>{
    
    {
    
     parentData }}</h1>
    <Child ref="child" />
    <button @click="$refs.child.add()">父级按钮</button>
  </div>
</template>

<script setup>
import Child from './Child.vue'
import {
    
     ref, onMounted } from 'vue'
const child = ref(null)
const parentData = ref('This is the parent data')
onMounted(() => {
    
    
  parentData.value = child.value.message
})
</script>

点击按钮2下,在父组件页面展示的效果:

在这里插入图片描述

总结:

defineExpose 用于在 <script setup> 中显式暴露组件内部状态和方法
父组件可以通过 ref 访问子组件实例并调用暴露的属性和方法
使用 defineExpose 可以让组件更加模块化和可控,只有显式暴露的部分才能被外部访问,增强了封装性和安全性
这个功能在组件之间需要进行复杂交互时特别有用,尤其是在大型项目中,能够显著提升代码的可读性和可维护性

猜你喜欢

转载自blog.csdn.net/weixin_47389477/article/details/141722829