在 Vue 3.2+ 版本中,可以使用 <script setup> 替代傳統(tǒng)的 script標(biāo)簽來編寫組件,它提供了更簡潔的語法來編寫 Composition API 代碼。
在 <script setup> 中,使用 defineProps 和 defineEmits時(shí)需要注意:
- 如果顯式地導(dǎo)入defineProps時(shí),在編譯時(shí)會提示以下wanning
<script steup>
import { defineProps } from 'vue';
...
</script>
開發(fā)環(huán)境編譯時(shí)會提示
[@vue/compiler-sfc] `defineProps` is a compiler macro and no longer needs to be imported.
原因是在 <script setup>中,defineProps 和 defineEmits 現(xiàn)在是編譯器宏(compiler macros),這意味著你不再需要顯式地從 'vue' 包中導(dǎo)入它們。這些宏在 <script setup> 的上下文中是自動可用的。文章來源:http://www.zghlxwxcb.cn/news/detail-851383.html
- 如果不顯式導(dǎo)出有可能提示以下錯誤
ERROR Failed to compile with 1 error
[eslint]
40:1 error 'defineProps' is not defined no-undef
要解決以上問題,既不重復(fù)導(dǎo)入又不在編譯時(shí)提示warning,可以在package.json里添加一行配置:
package.json文章來源地址http://www.zghlxwxcb.cn/news/detail-851383.html
...
"eslintConfig": {
"root": true,
"env": {
"node": true,
"vue/setup-compiler-macros": true #添加這行配置
},
...
到了這里,關(guān)于vue3在構(gòu)建時(shí),使用魔法糖語法時(shí)defineProps和defineEmits的注意事項(xiàng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!