学习优先度:★★★☆☆
难易度:★★☆☆☆
通过 Vue 3 中的 expose API,您可以将组件实例的特定属性和方法暴露给它的父组件,从而更方便地从外部与组件进行交互。
下面是一个示例,说明如何使用 expose API 将子组件的一个方法暴露给父组件。
【代码示例】
<!-- ChildComponent.vue -->
<template>
<div>
<p>{{ message }}</p>
<button @click="updateMessage">Update Message</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { expose } from '@vue/runtime-core';
const message = ref('Hello, World!');
function updateMessage() {
message.value = 'Message Updated!';
}
expose({
updateMessage
});
</script>
<!-- ParentComponent.vue -->
<template>
<div>
<ChildComponent ref="child" />
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const child = ref(null);
function callChildMethod() {
if (child.value) {
child.value.updateMessage();
}
}
</script>
【执行结果】
当点击父组件中的 "Call Child Method" 按钮时,会触发子组件中的 "updateMessage" 方法,更新子组件中显示的信息。
在本例中,子组件使用 expose API 来公开 updateMessage 方法。然后,父组件可以通过模板 ref 访问子组件的实例来调用该方法。这对于在组件中封装逻辑,同时允许父组件与之交互特别有用。
【补充】
expose API 是 Vue 3 的 Composition API 的一部分,旨在对组件外部可访问的属性和方法进行细粒度控制。这有助于维护封装,防止与内部组件状态发生意外交互。