重點(diǎn)
使用 defineExpose 來(lái)導(dǎo)出方法文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-805569.html
// child
<script setup>
import { ref, Ref } from 'vue'
const prop: Ref<string> = ref('child')
const method = (val: string) => {
console.log(val)
}
defineExpose({
prop,
method,
})
</script>
// father
<template>
<child ref="child" />
</template>
<script setup>
import { ref } from 'vue'
import child from './child.vue'
const child = ref<InstanceType<typeof child>>()
child.value.method(child.value.prop)
</script>
詳解
< script setup> 組件時(shí)默認(rèn)不導(dǎo)出屬性方法的(類似 java 的 private ),即通過(guò) ref 獲取實(shí)例是無(wú)法訪問(wèn)到自定義的屬性和方法,但是可以獲取到組件實(shí)例。
可以通過(guò) defineExpose 來(lái)指定要暴露的方法屬性,便可以在外部訪問(wèn)到組件自定義的屬性方法了。
當(dāng)然也可以去官網(wǎng)查看官方說(shuō)法。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-805569.html
到了這里,關(guān)于vue3使用自定義組件內(nèi)方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!