【Vue3】defineExpose 实践

【Vue3】defineExpose 实践

defineExpose 是 Vue 3 的 <script setup> 语法糖中提供的一个函数,用于显式地暴露组件的属性、方法或其他响应式状态给其父组件或外部使用。这是在使用 <script setup> 语法时,控制组件公开哪些内部状态和方法的一种方式。

在 Vue 3 的 <script setup> 中,默认情况下,组件内部定义的变量、方法等都不会被自动暴露给外部。这意味着,如果你想在父组件中通过模板引用(template refs)或其他方式访问子组件的方法或状态,你需要使用 defineExpose 来明确指明哪些是可被外部访问的。

使用示例

假设你有一个子组件,它有一个方法 resetForm 和一个状态 count,你希望这个方法和状态能在父组件中被直接访问。你可以使用 defineExpose 来实现这一点:

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

const count = ref(0)

function increment() {
    
    
  count.value++
}

function resetForm() {
    
    
  console.log('Form has been reset.')
}

// 使用 defineExpose 显式暴露属性和方法
defineExpose({
    
    
  resetForm,
  count
})
</script>

在父组件中,如果你使用了上述子组件,并且想要在某个事件(比如点击一个按钮)时调用子组件的 resetForm 方法或访问 count 状态,你可以这样做:

<template>
  <ChildComponent ref="childComp" />
  <button @click="resetChildForm">Reset Form in Child</button>
  <button @click="logChildCount">Log Child Count</button>
</template>

<script setup>
import {
    
     ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

const childComp = ref(null)

function resetChildForm() {
    
    
  childComp.value.resetForm()
}

function logChildCount() {
    
    
  console.log(childComp.value.count)
}
</script>

这里,ChildComponent 的 resetForm 方法和 count 状态被通过 defineExpose 暴露出去,因此父组件可以通过对子组件的引用 (childComp) 直接访问它们。

注意事项
defineExpose 仅在使用 <script setup> 语法时可用。
它提供了一种显式的方式来定义哪些内部状态或方法可以被外部访问,有助于提高代码的可维护性和可读性。
如果你没有使用 <script setup> 语法,而是使用了传统的 <script> 方式定义组件,那么组件的方法和属性可以通过在组件实例上定义来直接暴露给外部使用,不需要 defineExpose。

猜你喜欢

转载自blog.csdn.net/m0_56699208/article/details/136651119