<script setup>
是在单文件组件 (SFC) 中使用
组合式 API 的编译时语法糖。相比于普通的
<script>
语法,它具有更多优势:
- 更少的样板内容,更简洁的代码。
- 能够使用纯 Typescript 声明 props 和抛出事件。
- 更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。
- 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。
说白了就是对于setup()函数的简写
基本语法用法
要使用这个语法,需要将 setup attribute 添加到
<script setup>
console.log('hello script setup')
</script>
里面的代码会被编译成组件 setup() 函数的内容。这意味着与普通的 <script>
只在组件被首次引入的时候执行一次不同,<script setup>
中的代码会在每次组件实例被创建的时候执行
组件自动注册
不用在components属性中注册,直接可以使用
<template>
<Child />
</template>
<script setup>
import Child from './Child.vue'
</script>
数据、方法不需要return
<template>
<button @click="fun">{{name}}</button>
</template>
<script setup>
import {ref} from 'vue'
const name = ref('张三')
const fun = function(){
console.log('hello')
}
</script>
defineProps 和 defineEmits
在 <script setup>
中必须使用defineProps
和 defineEmits
API 来声明props
和 emits
,它们具备完整的类型推断并且在<script setup>
中是直接可用的:
<script setup>
const props = defineProps({
foo: String
})
// 使用时props.foo取值
const emit = defineEmits(['change', 'delete'])
// 使用时emit('change','参数')
</script>
与普通的script一起使用
<script setup>
可以和普通的<script>
一起使用。普通的<script>
在有这些需要的情况下或许会被使用到:
- 无法在
<script setup>
声明的选项,例如 inheritAttrs 或通过插件启用的自定义的选项。 - 声明命名导出。
- 运行副作用或者创建只需要执行一次的对象。
两者可以一同使用,但最多分别只能使用一个