vue3中的defineExpose使用示例教程
簡介
使用 <script setup> 的組件是默認關閉的————即通過模板引用或者 $parent 鏈獲取到的組件的公開實例,不會暴露在任何在 <script setup> 中聲明的綁定
換句話說,如果一個子組件使用的是選項式 API 或沒有使用 <script setup> ,被引用的組件實例和該子組件的 this 完全一致,這意味著父組件對子組件的每一個屬性和方法都有完全的訪問權。
但是如果使用了 <script setup> 的組件,這種組件是默認私有的,也就是一個父組件無法訪問到一個使用了 <script setup> 的子組件中的任何東西,除非子組件在其中通過 defineExpose 宏顯式暴露:
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
// 像 defineExpose 這樣的編譯器宏不需要導入
defineExpose({
a,
b
})
</script>舉個栗子
父組件獲取子組件的實例,去觸發(fā)子組件實例身上的方法。

父組件
<template>
<div class="p-20 pb-0 mb-4">
<div>父組件</div>
<button class="mt-4" @click="handleClick">點我聚焦</button>
</div>
<Child ref="childeRef"></Child>
</template>
<script setup lang="ts">
import { ref, provide, onMounted } from "vue";
import Child from "./Child.vue";
const childeRef = ref<HTMLInputElement | null>(null);
const handleClick = () => {
childeRef.value?.inputRef?.focus();
};
</script>子組件
<template>
<hr />
<div class="p-20 pt-4">
<div>子組件</div>
<input
ref="inputRef"
placeholder="請輸入哈哈哈哈"
class="border-1 mt-4"
/><br />
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const inputRef = ref<HTMLInputElement | null>(null);
defineExpose({
inputRef,
});
</script>參考文檔:
https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
https://cn.vuejs.org/guide/essentials/template-refs.html#ref-on-component
到此這篇關于vue3中的defineExpose使用的文章就介紹到這了,更多相關vue3 defineExpose使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue使用html2canvas實現(xiàn)將DOM節(jié)點生成對應的PDF
這篇文章主要為大家詳細介紹了vue如何使用html2canvas實現(xiàn)將DOM節(jié)點生成對應的PDF,文中的示例代碼簡潔易懂,感興趣的小伙伴可以學習一下2023-08-08
vue使用require.context實現(xiàn)動態(tài)注冊路由
這篇文章主要介紹了vue使用require.context實現(xiàn)動態(tài)注冊路由的方法,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12

