TypeScript
如今越来越多的大型项目和团队选择了 TypeScript 作为主力开发语言,GitHub 发布 2018 编程语言 TOP10 中,TypeScript 在开源贡献者使用最多的语言中排名跃居第七。除此之外,在前端开发群体中最受欢迎的编辑器之一 VS Code 就是基于 TypeScript 开发,三大框架之一的 Angular、著名后端框架 NestJS、机器学习框架 tfjs 都是基于 TypeScript 开发。
我们可以想象 Vue3.0 正式发布之后整个大型项目的生态会继续向 TypeScript 倾斜,可以说学习 TypeScript 已经是不可逆的趋势,但是与此同时我们发现在学习 TypeScript 过程中会踩到很多坑所以在这里我给大家写几个vue项目必备的用法
1.TypeScript的安装
安装指令
npm install -g typescript
下面是创建项目所选择的类型
下面给大家写几个案例可以参考一下ts + Vue3.0 + setup + volar的实用方法
<template>
<div class="home">
<h1>vue+ts+setup+volar</h1>
<button @click="addCount(2)">{{count}}</button>
<button>{{num}}</button>
<button v-if="flag">{{str}}</button>
<div v-for="(item,index) in list" :key="index">{{item}}</div>
<step :value="5" :max="20" :min="1" :step="2"></step>
</div>
</template>
<script lang="ts" setup>
import step from '@/components/StepCom.vue'
// javascript 数据类型 number string boolean undefined null
// JavaScript 引用类型:数组 对象 function函数类型
// ts:any任意类型,void没有返回值,interface接口
// 一.声明变量
import {ref,reactive} from 'vue'
const count = ref<number>(10);
const num = ref(5)
const str = ref<string>("i love ts")
const flag = ref<boolean>(true)
function addCount(n:number):void{
count.value+=n;
}
// 声明一个接口
interface Iuser{
name:string,
age:number,
pet:undefined|string
}
const list = reactive<Iuser>({name:"mumu",age:18,pet:"dog"})
</script>
<template>
<div>
<button :disabled="count<=props.min" @click="countChange(-1)">-</button>
<input type="text" v-model.number="count">
<button @click="countChange(1)" :disabled="count>=props.max">+</button>
</div>
</template>
<script lang="ts" setup>
// define 定义 props属性 ref引用
import { defineProps,ref } from 'vue';
interface Iprops{
max:number,
min:number,
step:number,
value:number,
}
const props = defineProps<Iprops>()
const count = ref<number>(props.value)
function countChange(n:number):void{
count.value += props.step*n;
}
</script>
下面图片里面是案例所展示的效果