TS

一、基础类型

1、字符串、数字、布尔、数组、对象、undefined、null、元祖

let a: string = "123";

let b: number = 123;

let c: boolean = true;

let d: Array = [333];

let d2: number[] = [3233];

let e: object = { a: "123" };

let u: undefined = undefined;

let n: null = null;

// 元祖

let yuanzu: [string, number] = ["123", 456];

// 元祖:先定义类型再引用

type yuanzu2 = [string, string, number];

let yuanzu3: yuanzu2 = ["1", "2", 3];

2、枚举

枚举 enum是js补充的一种数据类型,可以为数值赋予友好的名称

(1)数字枚举

// 数字枚举 元素编号从零开始

enum Color {

red,

blue,

black,

}

let ce: Color = Color.red;

console.log(ce); //0

// 数字枚举也可以为元素设置数值

enum Color2 {

red = 10,

blue,

black,

}

let cr: Color2 = Color2.red;

console.log(cr); //10

console.log(Color2.black); //12

// 数字枚举也可以通过数值获取元素

let cblack = Color2[12];

console.log(cblack); //black

console.log(Color2[11]); //blue

(2)常量枚举

const enum qq {

q,

w,

e,

t,

}

let ww: qq = qq.q;

console.log(ww);//0

(3) 异构枚举

enum yigou {

a,

b,

c = "c",

d = "d",

r = 1,

de,

}

let yd: yigou = yigou.de;

console.log(yd);//2

3、any

表示任意类型,可以在刚开始不知道后面会是什么类型时定义,类型检查器不会检查any类型所以类型不会报错

let test1: any = 1;

console.log("test1" + test1); //1

test1 = "test1";

console.log(test1); //test1

test1 = false;

console.log(test1); //false

4、unknown

表示任意类型,

let test1: any = 1;

console.log("test1" + test1); //1

test1 = "test1";

console.log(test1); //test1

test1 = false;

console.log(test1); //false

5、any 和 unknown

any 会增加运行时的风险,建议首先使用unknown

let wwq: unknown;

// let bb: number = wwq; 报错

// let bb: string = wwq;//报错

let bb: any = wwq; // undefined

let ccc: unknown = wwq; //undefuned

console.log(bb, ccc);

let mm: any;

let nn: number = mm;

console.log(nn); // undefined

let vvv: unknown = mm;

console.log(vvv); //undefined

6、小写的object 和 大写的Object 和 {} 的类型区别,定义对象最好使用小写的object

// object 表示的是常规的 Javascript 对象类型,非基础数据类型。

let o: object;

o = { a: 1 }; //正确

// {toString: ƒ}

o = {

toString() {

return "2";

},

};

// o = null;//报错

// o = undefined;//报错

// o = true;//报错

console.log(o);

// {} 表示非 null/undefuned 的任意类型

let O: {};

O = { a: 2 }; //正确

O = true; //正确

O = "123"; //正确

O = []; //正确

// {toString: ƒ}

O = {

toString() {

return 333;

},

};

// O = null; //错误

// O = undefined; //错误

console.log(O);

// Object基本和{}一样,但是会对Object原型内置方法(toString/hasOwnPreperty)进行检验

let O1: Object;

O1 = { a: 2 }; //正确

O1 = true; //正确

O1 = "123"; //正确

O1 = []; //正确

// {toString: ƒ}

O1 = {

toString() {

return "2";

},

};

// 报错

// O1 = {

// toString() {

// return 333;

// },

// };

// O1 = null; //错误

// O1 = undefined; //错误

console.log(O1);

7、void 和never

// void 一般用于表示函数中没有返回结果

function hh(): void {

console.log("ee");

}

hh();

// never 类型表示的是那些永不存在的值的类型

function nnFn(message: string): never {

throw new Error(message);

}

nnFn("3");

Vue3

一、 RouteRecordRaw

是vue-router 的一种数据类型,用来定义路由的类型。

二、defineComponent

defineComponent 是Vue3专门用于服务TS的,没有任何逻辑。会传入的Object 直接返回,可以把普通的对象转化为对应的数据类型。

三、computed 和 watch

四、store

// store/index.ts

import { createStore } from "vuex";

import mapModules from "./modules/mapModules";

export default createStore({

state: {},

mutations: {},

actions: {},

modules: {

mapModules,

},

});

// store/modules/mapModules.ts

import { createStore } from "vuex";

import mapModules from "./modules/mapModules";

import moment from "moment";

let ed = moment().format("YYYY-MM-DD");

let sd = moment(ed).add(-6, "day").format("YYYY-MM-DD");

const state = {

leafletMap: null,

// 切换地图

switchMapVal: "lsw2",

// 地图上的时间轴

timeRangeParams: {

curTime: "",

timeType: "h",

timeRange: {

end: ed,

start: sd,

},

allWidth: "",

},

};

const getters = {

leafletMap(state: any) {

return state.leafletMap;

},

// 切换地图

switchMapVal(state: any) {

return state.switchMapVal;

},

};

const mutations = {

setLeafletMap(state: any, leafletMap: any) {

//自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);

state.leafletMap = leafletMap;

},

// 切换地图

setSwitchMapVal(state: any, switchMapVal: string) {

state.switchMapVal = switchMapVal;

},

// 地图时间轴切换逐日逐时

changeTimeType(state: any, timeType: string) {

state.timeRangeParams.timeType = timeType;

},

// 地图时间轴选中日期被修改

changCurTime(state: any, curTime: string) {

state.timeRangeParams.curTime = curTime;

},

};

const actions = {

setLeafletMap(context: any, leafletMap: any) {

//同上注释,num为要变化的形参

context.commit("setLeafletMap", leafletMap);

},

};

export default {

namespaced: true, //用于在全局引用此文件里的方法时标识这一个的文件名

state,

getters,

mutations,

actions,

};

// 使用.vue

import { useStore } from 'vuex';

const store = useStore();

const map = store.state.mapModules.leafletMap;

console.log(map)

store.dispatch('mapModules/setLeafletMap', map)

let switchMapVal = ref('e')

store.commit('mapModules/setSwitchMapVal', switchMapVal.value)

五、request

import axios, { AxiosInstance, AxiosRequestConfig } from "axios";

import { ElMessage } from "element-plus";

// import { useUserStore } from "@/store/user";

class Api {

instance: AxiosInstance;

config: AxiosRequestConfig;

constructor(option: AxiosRequestConfig) {

this.config = option;

// 配置全局参数

this.instance = axios.create(this.config);

this.interceptors();

}

interceptors() {

this.instance.interceptors.request.use(

(config) => {

removePending(config);

addPending(config);

// 第三方登录

const token = sessionStorage.getItem("x-rbac-token");

if (token) {

config.headers["x-rbac-token"] = token;

}

return config;

},

(error) => Promise.reject(error)

);

this.instance.interceptors.response.use(

(response) => {

removePending(response.config);

const res = response.data;

// 有的接口没有按照code:0 为正确的格式返回

// if (res.code !== 1) {

// ElMessage.error(res.msg);

// }

return res;

},

(error) => {

error.config && removePending(error.config);

httpErrorStatusHandle(error);

return Promise.reject(error);

}

);

}

async request(config: AxiosRequestConfig): Promise {

return this.instance.request(config);

}

}

const api = new Api({

// baseURL: "/api",

timeout: 10 * 1000,

});

export default api;

/**

* 处理异常

* @param {*} error

*/

function httpErrorStatusHandle(error: any) {

// const userStore = useUserStore();

// 处理被取消的请求

if (axios.isCancel(error))

return console.error("请求的重复请求:" + error.message);

let message = "";

if (error && error.response) {

switch (error.response.status) {

case 302:

message = "接口重定向了!";

break;

case 400:

message = "参数不正确!";

break;

case 401:

// userStore.clearLoginInfo();

message = "您未登录,或者登录已经超时,请先登录!";

break;

case 403:

message = "您没有权限操作!";

break;

case 404:

message = `请求地址出错: ${error.response.config.url}`;

break; // 在正确域名下

case 408:

message = "请求超时!";

break;

case 409:

message = "系统已存在相同数据!";

break;

case 500:

message = "服务器内部错误!";

break;

case 501:

message = "服务未实现!";

break;

case 502:

message = "网关错误!";

break;

case 503:

message = "服务不可用!";

break;

case 504:

message = "服务暂时无法访问,请稍后再试!";

break;

case 505:

message = "HTTP版本不受支持!";

break;

default:

message = "异常问题,请联系管理员!";

break;

}

}

if (error.message.includes("timeout")) message = "网络请求超时!";

if (error.message.includes("Network"))

message = window.navigator.onLine ? "服务端异常!" : "您断网了!";

ElMessage({

type: "error",

message,

});

}

const pendingMap = new Map();

/**

* 储存每个请求的唯一cancel回调, 以此为标识

* @param {*} config

*/

function addPending(config: AxiosRequestConfig) {

const pendingKey = getPendingKey(config);

config.cancelToken =

config.cancelToken ||

new axios.CancelToken((cancel) => {

if (!pendingMap.has(pendingKey)) {

pendingMap.set(pendingKey, cancel);

}

});

}

/**

* 删除重复的请求

* @param {*} config

*/

function removePending(config: AxiosRequestConfig) {

const pendingKey = getPendingKey(config);

if (pendingMap.has(pendingKey)) {

const cancelToken = pendingMap.get(pendingKey);

// 如你不明白此处为什么需要传递pendingKey可以看文章下方的补丁解释

cancelToken(pendingKey);

pendingMap.delete(pendingKey);

}

}

/**

* 生成唯一的每个请求的唯一key

* @param {*} config

* @returns

*/

function getPendingKey(config: AxiosRequestConfig) {

let { url, method, params, data } = config;

if (typeof data === "string") data = JSON.parse(data); // response里面返回的config.data是个字符串对象

return [url, method, JSON.stringify(params), JSON.stringify(data)].join("&");

}

使用request

// /api/mapData.ts

import http from "@/utils/request";

const sereenName: string = "/sereen";

const VUE_APP_OSS_URL: string = "http://makenv-obs-interpolation.file-server.makenv.com";

class MapDataApi {

// 风场

getWind(params: any) {

return http.request({

url: VUE_APP_OSS_URL + "/gfs0p25-wind/" + params.year + "/fnl_" + params.time + ".json",

method: "GET",

});

}

/**

* 获取成都边界线

* @returns

*/

getGeoJson() {

return http.request({

url: "../../json/geojson.json",

method: "GET",

});

}

// 获取登录信息

getTokenUser(code: string | (string | null)[]) {

return http.request({

url: "/login/screen/login?code=" + code,

method: "get",

});

}

/**

* 保存接口

* @param params 保存参数

* @returns

*/

saveOrUpdate(params: object) {

return http.request({

url: "/sys/userInfo/saveOrUpdate",

method: "POST",

data: params,

});

}

}

const mapDataApi = new MapDataApi();

export default mapDataApi;

// mapdata.vue

import mapDataApi from '@/api/mapData';

let res = await mapDataApi.getWind(params);

参考阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。
大家都在看: