项目使用TypeScript的前置工作
webpack打包配置
- entry配置项:入口文件。
- extentions:加上TS文件area,用于处理尝试的数据尾缀列表,即可处理的文件类型是什么。
- loaders:是每一个模块拓展的地方,微内核架构的核心思想。加上’ts-loader’,增加对于TS的处理,对TS进行编译时的编译。
TS本身的配置
在tsconfig.json中配置。相关重点配置项如下:
- jsx:支持JSX语法。
- allowSyntheticDefault:允许没有默认export的模块中默认import进来。
- experimentalDecorators:启用装饰器。
使用 vue / vuex + TypeScript 搭建项目基础(和使用JavaScript不同的点)
- 定义组件的方式上:最好使用extends方式。
//没有使用extends方式
const Component = {
//缺点:TS无法断定内部为vue组件,需要做额外的声明处理,如Vue.prototype.xxx形式。
};
//声明当前组件模块 Vue.component or Vue.extend
import Vue from 'vue';
const Component = Vue.extend({
//类型推断
});
- 使用vue-class-component方式定义组件,使用全面拥抱面向对象的方式,官方推荐。
import Component from 'vue-class-component'
// @Component本质:是一个类装饰器,利用装饰器统一描述vue模板等概念
@Component({
template: '<vueComponent/>'
})
export default class myComponent extends Vue {
message: string = 'hello';
onClick(): void {
console.log(this.message);
}
}
- 利用ts的额外补充模块declare声明组件 => 实现独立模块的声明,使之可以被独立引用。
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
};
// 补充模块方式:通常使用.d.ts来做声明描述。给vue补充了这些方面的功能,使之可以在声明vue实例时使用添加在module上的属性方法等。
declare module '/typings/vuePlugin.d.ts' {
interface Vue {
myProps: string;
}
}
// 实例中使用
let vm = new Vue();
console.log(vm.myProps);
- 传参问题:props - vue提供了propType原地声明复合变量。
import {
propType } from 'vue';
interface customPayload {
str: string,
number: number,
name: string
};
const Component = Vue.extend({
props: {
name: string, //字符串类型
success: {
type: string }, //普通对象类型
payload: {
type: Object as propType<customPayload>
},
callback: {
type: Function as propType<() => void>
}
}
});
- computed、method:如果其中使用到了this且return的方法,需要声明返回类型。
computed: {
getMsg(): string {
return this.click() + '!';
}
}
methods: {
click(): string {
return this.message + '~';
}
}
- vuex中使用ts - vuex.d.ts中声明模块(ComponentCustomProperties)、接口形式使用。
import {
ComponentCustomProperties } from 'vue'
declare module '@vue/runtime-core' {
interface State {
count: number;
}
interface ComponentCustomProperties {
$store: Store<State>
}
}
- 使用vuex方式2:api形式编码实现 - 官方推荐。本质是依赖注入方式provider & inject。
//store.ts
import {
InjectionKey } from 'vue';
import {
createStore, Store } from 'vuex';
export interface State {
count: number;
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
state: {
count: 0;
}
});
//main.ts
import {
createApp } from 'vue';
import {
store, key } from './store';
const app = createApp({
//传入参数
});
//利用了provider & inject方式
app.use(store, key); // => 传入injection Key
app.mount('#app');
//消费方,某一个.vue组件中
import {
useStore } from 'vuex';
import {
key } from './store';
export default {
const store = useStore(key);
store.state.count;
};
// 标准接口形式的功能引入,核心利用了vue的provide&inject
- 利用vuex-class方式,vuex的面向对象。
import {
State, Action, Getter } from "vuex-class";
export default class App extends Vue {
// 属性装饰器,整合了store状态
@State login: boolean;
// 事件装饰器,整合了store方法
@Action setInit: () => void;
get isLogin: boolean;
mounted() {
this.setInit();
}
}