一、Vue3.x集成Typescript
npm install --global @vue@cli
vue create my-project-name
vue add typescript
# 会出现命令行,让其选择 第一个选 N 其余都选y
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MdXz0QSL-1630392635969)(./images/添加ts.png)]
二、在Vue里使用TS
<template>
<h1>{{title}}</h1> <br>
<button @click="setCount">修改count</button>
count={{count}}
<br>
{{reverseTitle}}
</template>
<!-- 设置语言为ts -->
<script lang="ts">
import {defineComponent} from 'vue'
// 定义数据接口,可以对key进行校验
interface News {
title: string,
desc: string,
count: number | string, // 指定count可以为number或string类型
content?: string
}
// 定义数据
// let newData: News = {
// title: "我是一个新闻标题",
// desc: "我是一个新闻描述",
// count: 12
// };
// 表示实现了该接口
let newData = {
title: "我是一个新闻标题",
desc: "我是一个新闻描述",
count: 12
} as News;
export default defineComponent({
name: "News",
data() {
return newData
},
methods: {
setCount(): void {
this.count = 122;
}
},
computed: {
reverseTitle(): string {
return this.title.split("").reverse().join("");
}
}
})
</script>
<style scoped>
</style>
三、组合式API里使用TS
<template>
<div>
User组件
<button @click="setUsername('旺旺')">修改username</button>
username:{{username}} --- age:{{age}}
count:{{count}}
</div>
</template>
<script lang="ts">
import {defineComponent, reactive, toRefs, ref} from 'vue'
// 定义接口
interface User {
username: string,
age: number,
setUsername(username: string): void,
getUsername(): string
}
export default defineComponent({
name: "User",
setup() {
// 第一种写法
// let user: User = reactive({
// username: "涨三",
// age: 10,
// setUsername(username: string): void {
// this.username = username;
// },
// getUsername(): string {
// return this.username
// }
// });
// 第二种方法
// let user = reactive<User>({
// username: "涨三",
// age: 10,
// setUsername(username: string): void {
// this.username = username;
// },
// getUsername(): string {
// return this.username
// }
// });
// 第三种方法
let user = reactive<User>({
username: "涨三",
age: 10,
setUsername(username: string): void {
this.username = username;
},
getUsername(): string {
return this.username
}
}) as User;
// ref 这样去定义
let count = ref<number | string>("123");
return {...toRefs(user), count};
}
})
</script>
<style lang="scss" scoped>
</style>
四、禁用eslint
在package.json里的eslint里添加配置
"rules": {
"generator-star-spacing": "off",
"no-tabs":"off",
"no-unused-vars":"off",
"no-console":"off",
"no-irregular-whitespace":"off",
"no-debugger": "off"
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vzr7Oyyt-1630392635975)(./images/禁用eslint.png)]