vue3在构建时,使用魔法糖语法时defineProps和defineEmits的注意事项

在 Vue 3.2+ 版本中,可以使用 <script setup> 替代传统的 script标签来编写组件,它提供了更简洁的语法来编写 Composition API 代码。

在 <script setup> 中,使用 defineProps 和 defineEmits时需要注意:

  1. 如果显式地导入defineProps时,在编译时会提示以下wanning
<script steup>
import { defineProps } from 'vue';
...
</script>

开发环境编译时会提示

[@vue/compiler-sfc] `defineProps` is a compiler macro and no longer needs to be imported.

原因是在 <script setup>中,defineProps 和 defineEmits 现在是编译器宏(compiler macros),这意味着你不再需要显式地从 'vue' 包中导入它们。这些宏在 <script setup> 的上下文中是自动可用的。

  1. 如果不显式导出有可能提示以下错误
 ERROR  Failed to compile with 1 error

[eslint] 
  40:1  error  'defineProps' is not defined  no-undef

要解决以上问题,既不重复导入又不在编译时提示warning,可以在package.json里添加一行配置:
package.json

  ...
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true,
      "vue/setup-compiler-macros": true #添加这行配置
    },
...
posted @ 2024-04-14 17:41  小透明落在星田  阅读(114)  评论(0编辑  收藏  举报