vue3?使用defineExpose的實(shí)例詳解
可以通過 defineExpose
編譯器宏來顯式指定在 <script setup>
組件中要暴露出去的屬性:
<script setup> import { ref } from 'vue' const a = 1 const b = ref(2) defineExpose({ a, b }) </script>
當(dāng)父組件通過模板引用的方式獲取到當(dāng)前組件的實(shí)例,獲取到的實(shí)例會(huì)像這樣 { a: number, b: number }
(ref 會(huì)和在普通實(shí)例中一樣被自動(dòng)解包)
例子
父組件
<template> <h2>defineExpose 使用 父組件</h2> <child ref="getChildData"></child> </template> <script setup lang="ts"> import Child from "@/components/exposeChildren.vue" import { ref,onMounted,toRaw} from 'vue' // 文檔說setup寫在script上組件是關(guān)閉的 // 也就是說父組件使用getChildData.xxx訪問不到子組件的數(shù)據(jù) // 此時(shí)我們需要用defineExpose把需要傳遞的數(shù)據(jù)暴露出去,這樣外部才能訪問到 // 同理也可以接收外部傳來的值 const getChildData = ref(null) const obj = { name: 'alan', desc: '大笨蛋', age: 18 } const cc= getChildData.value?.['num'] console.log(cc) //undefined,此時(shí)還未找到子組件暴露的數(shù)據(jù) onMounted(()=>{ //獲取子組件的data數(shù)據(jù),什么時(shí)候獲取根據(jù)自己業(yè)務(wù)來 const bb:any= getChildData.value?.['updata'] console.log(bb()) // 123,這時(shí)候得到的是子組件的初始值,因?yàn)檫€未給子組件傳遞數(shù)據(jù) const a:any= getChildData.value?.['getData'] a(obj) ////給子組件傳遞數(shù)據(jù) const b:any= getChildData.value?.['updata'] const c= getChildData.value?.['num'] console.log(toRaw(b())) // {name: 'alan', desc: '大笨蛋', age: 18} ,這里得到的是個(gè)proxy,所以需要toRaw()方法轉(zhuǎn)成對象 console.log(c) // 666 }) </script> <style scoped> </style>
子組件
<template> <h2>defineExpose 使用 子組件</h2> <div>{{ data }}</div> </template> <script setup lang="ts"> import { ref, defineExpose } from 'vue' const data = ref(123) const num = ref(666) defineExpose({ updata(){ return data.value //暴露出去父組件可以拿到data的數(shù)據(jù).此時(shí)值為123 }, getData(res:any){ data.value = res //父組件傳遞來的值賦值給data // 此時(shí)的data變成了 Proxy // { // name: 'alan', // desc: '大笨蛋', // age: 18 // } }, num }) </script> <style scoped> </style>
到此這篇關(guān)于vue3 使用defineExpose的文章就介紹到這了,更多相關(guān)vue3 使用defineExpose內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue+webpack+Element 兼容問題總結(jié)(小結(jié))
這篇文章主要介紹了Vue+webpack+Element 兼容問題總結(jié)(小結(jié)),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08vue實(shí)現(xiàn)tab切換的3種方式及切換保持?jǐn)?shù)據(jù)狀態(tài)
這篇文章主要給大家介紹了關(guān)于vue實(shí)現(xiàn)tab切換的3種方式及切換保持?jǐn)?shù)據(jù)狀態(tài)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05vue自定義權(quán)限指令的實(shí)現(xiàn)
本文主要介紹了vue自定義權(quán)限指令的實(shí)現(xiàn)2024-05-05vue-image-crop基于Vue的移動(dòng)端圖片裁剪組件示例
這篇文章主要介紹了vue-image-crop基于Vue的移動(dòng)端圖片裁剪組件示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08