<script setup>
是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的 <script>
语法,它具有更多优势:
- 更少的样板内容,更简洁的代码。
- 能够使用纯 TypeScript 声明 props 和自定义事件。
- 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
- 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。
1.基本语法
<script>
代码块上添加 setup
<script setup>
</script>
1.顶层的绑定会被暴露给模板
当使用 <script setup>
的时候,任何在 <script setup>
声明的顶层的绑定 (包括变量,函数声明,以及 import 导入的内容,包含引用的组件) 都能在模板中直接使用:
<script setup>
import MyComponent from './MyComponent.vue' //组件
// 变量 const msg = '按钮'
// 函数 const ClickBtn = ()=> { console.log(msg) }
</script>
<template>
<button @click="ClickBtn">{{ msg }}</button>
<MyComponent />
</template>
2.defineProps()
和 defineEmits()
props
和 emits
选项时获得完整的类型推导支持,我们可以使用 defineProps
和 defineEmits
API,它们将自动地在 <script setup>
中可用
<script setup>
const props = defineProps({ foo: String })
const emit = defineEmits(['change', 'delete']) // setup 代码
</script>
或
const props = defineProps<{ foo: string bar?: number }>()
const emit = defineEmits<{ (e: 'change', id: number): void (e: 'update', value: string): void }>()
使用类型声明时的默认 props 值
export interface Props { msg?: string labels?: string[] }
const props = withDefaults(defineProps<Props>(), { msg: 'hello', labels: () => ['one', 'two'] })
3.顶层 await
<script setup>
中可以使用顶层 await
。结果代码会被编译成 async setup()
<script setup>
const post = await fetch(`/api/post/1`).then((r) => r.json())
</script>
4.限制:
由于模块执行语义的差异,<script setup>
中的代码依赖单文件组件的上下文。当将其移动到外部的 .js
或者 .ts
文件中的时候,对于开发者和工具来说都会感到混乱。因此,<script setup>
不能和 src
attribute 一起使用。意思就是外部引入的ts,参数和方法并不是共享的需要自行处理