外观风格
Vue3 组件声明
vue3 单文件组件(即 *.vue 文件,简称 SFC) 是一种特殊的文件格式,使我们能够将一个 Vue 组件的模板、逻辑与样式封装在单个文件中。
要在单文件组件中使用 typescript,有2种方式。
defineComponent
要使 typescript 正确推导出组件内的类型,无论是选项式 API 还是组合式 API,都需要借助 defineComponent
来完成。
选项式 API
除了 引入了 defineComponent
,其他的写法和 vue2 相似。
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
// 启用了类型推导
props: {
name: String,
msg: { type: String, required: true }
},
data() {
return {
count: 1
}
},
mounted() {
this.name // 类型:string | undefined
this.msg // 类型:string
this.count // 类型:number
}
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
组合式 API
组合式 API 是在 vue3 中推出的全新语法,开发方式更加灵活和自然。
TIP
关于组合式 API 的优势,可以查阅:https://staging-cn.vuejs.org/guide/extras/composition-api-faq.html#what-is-composition-api
而在组合式 API 中使用 typescript,需要使用 defineComponent() 和 setup()。
<script>
import { defineComponent } from 'vue'
export default defineComponent({
// 启用了类型推导
props: {
message: String
},
setup(props) {
props.message // 类型:string | undefined
}
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
<script setup>
<script setup>
是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时则推荐该语法。相比于普通的 <script>
语法,它具有更多优势:
- 更少的样板内容,更简洁的代码。
- 能够使用纯 Typescript 声明 prop 和抛出事件。
- 更好的运行时性能 (其模板会被编译成同一作用域的渲染函数,没有任何的中间代理)。
- 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。
使用 <script setup>
就无需借助 defineComponent。
<script setup lang="ts">
const props = defineProps({
foo: { type: String, required: true },
bar: Number
})
props.foo // string
props.bar // number | undefined
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
在 vue3 开发中,使用 setup
语法开发已是主流,后续教程,我们也将会以该语法为主,进行介绍。
技巧
script setup + ts = 真香💯