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

