使用 setup 语法糖编写组件定义 props

5,806 阅读1分钟

在 <script setup> 中必须使用 defineProps 和 defineEmits API 来声明 props 和 emits ,它们具备完整的类型推断并且在 <script setup> 中是 直接可用 的:

<script setup>
const props = defineProps({
  foo: String
})

const emit = defineEmits(['change', 'delete'])
// setup code
</script>

来自官方文档: 单文件组件

  • defineProps 和 defineEmits 都是只在 <script setup> 中才能使用的编译器宏。他们不需要导入且会随着 <script setup> 处理过程一同被编译掉。
  • defineProps 接收与 props 选项相同的值,defineEmits 也接收 emits 选项相同的值。
  • defineProps 和 defineEmits 在选项传入后,会提供恰当的类型推断。
  • 传入到 defineProps 和 defineEmits 的选项会从 setup 中提升到模块的范围。因此,传入的选项不能引用在 setup 范围中声明的局部变量。这样做会引起编译错误。但是,它可以引用导入的绑定,因为它们也在模块范围内。

不是说可以直接使用吗? 怎么报错了?

image.png

 error  'defineProps' is not defined  no-undef

解决

eslintrc.js 配置:

module.exports = {
  env: {
    'vue/setup-compiler-macros': true
  }
}

User Guide | eslint-plugin-vue (vuejs.org)