本文主要是讲解 <script setup>
与 TypeScript
的基本使用。
<script setup>
是什么?
<script setup>
是在单文件组件 (SFC) 中使用 composition api
的编译时语法糖。
本文写作时,vue
使用的 3.2.26 版本。
1.1. 发展历程
我们先看看 vue3 <script setup>
的发展历程:
Vue3
在早期版本(3.0.0-beta.21
之前)中对composition api
的支持,只能在组件选项setup
函数中使用。
<template>
<h1>{
{ msg }}</h1>
<button type="button" @click="add">count is: {
{ count }}</button>
<ComponentA />
<ComponentB />
</template>
<script>
import { defineComponent, ref } from 'vue'
import ComponentA from '@/components/ComponentA'
import ComponentB from '@/components/ComponentB'
export default defineComponent({
name: 'HelloWorld',
components: { ComponentA, ComponentB },
props: {
msg: String,
},
setup(props, ctx) {
const count = ref(0)
function add() {
count.value++
}
// 使用return {} 把变量、方法暴露给模板
return {
count,
add,
}
},
})
</script>
-
在 3.0.0-beta.21 版本中增加了
<script setup>
的实验特性。如果你使用了,会提示你<script setup>
还处在实验特性阶段。 -
在 3.2.0 版本中移除
<script setup>
的实验状态,从此,宣告<script setup>
正式转正使用,成为框架稳定的特性之一。
<script setup lang="ts">
import { ref } from 'vue'
import ComponentA from '@/components/ComponentA'
import ComponentB from '@/components/ComponentB'
defineProps<{ msg: string }>()
const count = ref(0)
function add() {
count.value++
}
</script>x
<template>
<h1>{
{ msg }}</h1>
<button type="button" @click="add">count is: {
{ count }}</button>
<ComponentA />
<ComponentB />
</template>
1.2. 优势
与组件选项 setup
函数对比, <script setup>
的优点:
- 更少、更简洁的代码,不需要使用
return {}
暴露变量和方法了,使用组件时不需要主动注册了; - 更好的
Typescript
支持,使用纯Typescript
声明props
和抛出事件,不会再像option api
里那么蹩脚了; - 更好的运行时性能;
当然, <script setup>
也是有自己的缺点的,比如需要学习额外的 API
。
那么 <script setup>
怎么使用呢?有哪些使用要点?与TypeScript如何结合?
2. 使用要点
2.1. 工具
Vue3
单文件组件 (SFC) 的 TS IDE
支持请用 <script setup lang="ts"> + VSCode + Volar
。
类型检查使用 vue-tsc
命令。
- VSCode:前端最好用的
IDE
。 - Volar:为
Vue3
的*.vue
单文件组件提供代码高亮、语法提示等功能支持的VSCode
插件;Vue2
你可能是使用的Vetur
插件,需要禁用Vetur
,下载Volar
,并启用它。 - vue-tsc:类型检查和
dts
构建命令行工具。
2.2. 基本用法
将 setup
属性添加到 <script>
代码块上。
<script setup>
import { ref } from 'vue'
defineProps({
msg: String
})
const count = ref(0)
function add() {
count.value++
}
</script>
<template>
<h1>{
{ msg }}</h1>
<button type="button" @click="add">count is: {
{ count }}</button>
</template>
若需要使用 TypeScript
,则将 lang
属性添加到 <script>
代码块上,并赋值 ts
。
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
function add() {
count.value++
}
</script>
<template>
<h1>{
{ msg }}</h1>
<button type="button" @click="add">count is: {
{ count }}</button>
</template>
<script setup>
块中的脚本会被编译成组件选项 setup
函数的内容,也就是说它会在每次组件实例被创建的时候执行。
在 <script setup>
声明的顶层绑定(变量、函数、import引入的内容),都会自动暴露给模板,在模板中直接使用。