最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue3?使用defineExpose的實例詳解

 更新時間:2023年03月18日 08:37:14   作者:冷風風  
這篇文章主要介紹了vue3?使用defineExpose的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

可以通過 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上組件是關(guān)閉的
    // 也就是說父組件使用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è)務(wù)來
  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()方法轉(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ù).此時值為123
    },
    getData(res:any){
        data.value = res //父組件傳遞來的值賦值給data
        // 此時的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)文章

最新評論

建湖县| 泸水县| 康定县| 新和县| 南宁市| 上思县| 玉林市| 牟定县| 正镶白旗| 宝应县| 驻马店市| 枝江市| 西华县| 毕节市| 盈江县| 通城县| 海伦市| 成安县| 酒泉市| 林州市| 巨鹿县| 弥渡县| 大冶市| 专栏| 邵阳县| 偏关县| 临武县| 专栏| 台前县| 图木舒克市| 毕节市| 乌拉特后旗| 祥云县| 白山市| 岑巩县| 柳林县| 余江县| 砚山县| 高雄县| 呼玛县| 江都市|