[Vue3] defineExpose要在方法宣告定義以后使用
Vue3中的setup默認是封閉的,如果要從子組件向父組件暴露屬性和方法,需要用到defineExpose.
和defineProps, defineEmits一樣,這三個函式都是內置的,不需要import.
不過defineProps, defineEmits都會回傳一個實體,而defineExpose是無回傳值的.
const props = defineProps({})
const emit = defineEmits([])
defineExpose({})
defineExpose的使用
子組件Child.vue
<template>
{{ name }}
</template>
<script setup>
import { ref } from 'vue'
const name = ref("Nicholas.")
const sayName = ()=>{
console.log("my name is "+name.value)
}
defineExpose({
name,
sayName
});
</script>
父組件Father.vue
<template>
<Child ref="child"></Child>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const child = ref(null)
onMounted(()=>{
console.log(child.value.name) // "Nicholas"
child.value.sayName() // "my name is Nicholas"
})
</script>
總結
-
向外暴露的時候變數會自動解包,比如上面子組件的
name:ref<String>暴露到父組件的時候自動變成了name:String. -
注:defineExpose一定要在變數和方法宣告定義之后再使用,
不知道以后會不會有修改,不過在
2023/02/17,如果defineExpose寫在變數和函式前面,那么瀏覽器的控制臺會輸出很多警告,并且最終將該頁面卡死,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/544220.html
標籤:其他
上一篇:JS、PHP回車輸入替換
下一篇:表格改成輪播表格效果
