Vue 3 <script setup> 语法糖

Vue 3 的 <script setup> 是一种编译时语法糖,用于简化组合式 API 的写法。它通过更简洁的语法实现组件逻辑的编写,同时保持类型推断和更好的 IDE 支持。

基本用法
<script setup>
import { ref, computed } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">{{ count }} ({{ doubled }})</button>
</template>
特性
  1. 自动暴露顶层绑定
    <script setup> 中声明的变量、函数和导入内容会自动暴露给模板,无需手动返回。

  2. 组件注册
    导入的组件可以直接在模板中使用,无需通过 components 选项注册。

    <script setup>
    import MyComponent from './MyComponent.vue'
    </script>
    <template>
      <MyComponent />
    </template>
    
  3. Props 和 Emits 声明
    使用 definePropsdefineEmits 编译器宏声明 props 和 emits:

    <script setup>
    const props = defineProps({
      title: String
    })
    const emit = defineEmits(['change'])
    </script>
    
  4. 默认插槽和作用域插槽
    通过 useSlotsuseAttrs 访问插槽和属性:

    <script setup>
    import { useSlots, useAttrs } from 'vue'
    const slots = useSlots()
    const attrs = useAttrs()
    </script>
    
  5. 顶层 await
    支持直接在 <script setup> 中使用 await

    <script setup>
    const data = await fetchData()
    </script>
    
与普通 <script> 对比
  • 更简洁:减少样板代码,无需手动返回数据和方法。
  • 更好的类型推断:与 TypeScript 集成更友好。
  • 性能优化:编译时静态分析,生成更高效的代码。
注意事项
  1. 无法与 <script> 混用(除非使用 lang="ts" 或其他非默认行为)。
  2. 某些工具链可能需要额外配置(如 Vite 或 Vue CLI)。
示例:组合式函数
<script setup>
import { useCounter } from './composables/useCounter'

const { count, increment } = useCounter()
</script>

<template>
  <button @click="increment">{{ count }}</button>
</template>

<script setup> 是 Vue 3 开发的首选方式,尤其适合组合式 API 和 TypeScript 项目。

更多推荐