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

vue3?使用defineExpose的實(shí)例詳解

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

可以通過 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)成對(duì)象 
  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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

轮台县| 德安县| 江华| 肇源县| 山东省| 锦屏县| 临城县| 郧西县| 天门市| 读书| 达州市| 永吉县| 台北县| 湟源县| 翁源县| 西城区| 肇东市| 盐源县| 汨罗市| 嫩江县| 邓州市| 浑源县| 垫江县| 朝阳县| 青冈县| 秭归县| 宣汉县| 澄迈县| 庐江县| 宁安市| 葫芦岛市| 平谷区| 旬邑县| 内黄县| 德州市| 曲周县| 静安区| 长子县| 绍兴市| 乐业县| 胶南市|