1. 前言
1.vue3现在其实很多公司已经用到了,今天捋一捋
2.默认你已经了解了TS的基础语法,不了解的也可以看之前写的几篇文章
3.TS语法-03
4.TS语法-04
2. 基本环境
就是简单的脚手架配置
vue create 项目名
可以选择默认 这里选择自定义配置 Manually select feature
tsv3.png
注意
Use class-style component syntax yes 选择了
yes
3. 使用TS 方式1 ---脚手架默认的
类似 Home或者about这样的写法
3.1 Home
import { Options, Vue } from 'vue-class-component';
import HelloWorld from '../components/HelloWorld.vue';
@Options({
components: {
HelloWorld
},
})
export default class Home extends Vue {}
3.2 HelloWorld
@Options({
props: {
msg: String,
},
})
export default class HelloWorld extends Vue {
msg!: string;
}
3.3 简要分析
- 如你所见 props类似之前的data
2.msg!:string
3.组件里面的 data可以像这样直接定义,
4.!
的意思是赋值断言
5.去掉报错
1.png
6.去掉的话会报错 没有进行初始化赋值
7.!
就是告诉编译器你不用操心了,将来肯定会有传参的
4. 使用TS 方式2----JSX语法
随意新建个
tsx
文件 例如yzs.tsx
4.1 tsx 文件内容
import { Options, Vue } from 'vue-class-component';
@Options({
props: {
msg: String
}
})
export default class World extends Vue {
// ! 赋值断言
// 去掉的话会报错 没有进行初始化赋值 ! 就是告诉编译器你不用操心了,将来肯定会有传参的
msg!: string
render(){
// 提示强悍
return {this.msg}
}
}
4.2 简要分析
tsx
后缀的文件可以使用JSX
的写法- 在
render
写内容会有对应的提示,
1.png
2.png
3.在
vue
文件中的模板中写可是没有对应的提示的
4.越来越像react
了,学起来吧
5.使用的时候也是直接导入/import
就行
5. 基本的循环写法
组件里面直接写 参照
msg
5.1 data数据
characters:string[] = ["类型注解","编译性的语言"]
5.2 运用
{{ msg }}
特性列表
-
{{ item}}
6. 类型别名
6.1 类型别名定义
type Character = {
id: number;
name: string;
};
6.2 用法
characters:Character[] = [{id:1,name:"类型注解"},{id:2,name:"编译性的语言"}]
6.3 使用的地方也需要更改
{{ item.name }}
不足之处就是 数据类型改了;使用的地方并不会进行报错
7. 交叉类型
7.1 交叉类型定义
type Character = {
id: number;
name: string;
};
type SelectCharacter = Character & { selected: boolean }
7.2 变量
characters: SelectCharacter[] = [
{ id: 1, name: "类型注解", selected: true },
{ id: 2, name: "编译性的语言", selected: false },
];
7.3 使用
{{ item.name }}
7.4 样式
.selected {
background-color: orange;
color: #fff;
}
8. 图示
1.png
参考资料
TS语法-03
TS语法-04