Typescript越来越火,网上的评论也对Typescript越吹越流弊,作为前端小白不去玩玩就有些落后了。
Vue的安装
这自行去Vue官网安装Vue-cli3
Typescript的安装
cnpm install typescript -g
vue项目配置Typescript
配置tsconfig.json(二选一)
- 可以typescript官网的tsc --init
- 也可以使用vue官网推荐的tsconfig.json
新增shims-vue.d.ts文件
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
这文件的作用是定义全局Vue变量
新增shims-tsx.d.ts文件
import Vue, { VNode } from 'vue';
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any;
}
}
var $: any;
}
这文件的作用就是定义全局变量(我直知道这个...)
新增index.d.ts文件
interface Window{
Utils: any
ReqUrl: object
reqUrl: any,
setValue: any,
$refs: any
}
这文件的作用就是定义window的全局变量
mian.js改为main.ts文件
安装vue和vuex在typescript的语法糖
cnpm i vue-class-component -S
cnpm i vue-property-decorator -S
cnpm i vuex-class -S
引入方法
import { Component, Prop, Vue, Emit} from 'vue-property-decorator';
import { State, Mutation, namespace} from 'vuex-class';
配置Vuex
配置state和mutations
let store : Store<any> = new Vuex.Store({
state: {
key: '',
tabIndex: 0
},
mutations: {
SET_STATE(state, payload){
for(let key in payload){
state[key] = payload[key];
}
}
},
})
配置getters
新建一个storeTypes.ts文件,这文件主要暴露getter的接口
export interface StateStore{
key: string,
tabIndex: number
}
新建getters.ts文件
import {StateStore} from './storeTypes';
const getters = {
key: (state: StateStore) => state.key,
tabIndex: (state: StateStore) => state.tabIndex,
}
export default getters
配置modules
新建一个indexModule.ts文件
// indexModule.ts
import { Module, VuexModule, Mutation } from 'vuex-module-decorators';
@Module({ name: 'index', namespaced: true, stateFactory: true })
export default class IndexModule extends VuexModule{
search = {
key: '',
ClassNum: "",
esSchoolId: "",
grade: "",
realName: "",
masterWxAccount: "",
masterId: "",
endDate: "",
startDate: "",
pageNumL: 1,
pageSizeL: 10
}
// 通过Mutation设置vuex的值
@Mutation
SET_SEARCH(payload: any){
for(let key in payload){
this.search[key] = payload[key]
}
}
// 通过getter暴露接口
get searchObejct(){
return this.search
}
}
// index.ts
modules: {
index: IndexModule
},
引用:
// 通过Getter获取vuex的值
@IndexModule.Getter('searchObejct') search!:any
// 通过Mutation设置vuex的值
@IndexModule.Mutation('SET_SEARCH')
Vuex与Typescript相结合
场景一
在Vue文件中获取vuex的state的变量,并且改变state的变量的值,这里改变state的值是通过
方法一
// Js文件的引入
this.$store.state
// Ts中的引入, 直接在文件中是index即可
@State(state => state.index) index!: object
方法二
通过getter来引入变量
@Getter('tabIndex') tabIndex!:number
场景二
在计算属性computed中引入vue的state变量,是通过getter来引入
... 未完待续
总结
优点:
- 在参数传值时候,不用再过多的判断参数的类型,防止了很多undefined和的问题。
- 在IDE上面有了许多友好的提示,让我们很快的发现错误
缺点:
- 给我感觉用起来好繁琐,可能在vue上吧,写起来很笨重
- 开发时间比之前多了,但是维护起来很容易