将Ts往Vue3中再整合一下

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

Dear,大家好,我是“前端小鑫同学”,😇长期从事前端开发,安卓开发,热衷技术,在编程路上越走越远~


00. 创建一个vue3+ts的基础工程:yarn create vite

01. Ts规范data的类型(类型断言):

  1. 使用type定义Todo的类型:
type Todo = {
id: number;
name: string;
};
  1. data中的属性这样来定义:
data() {
return {
items: [] as Todo[],
};
},
  1. 类型推断正常并提示:

image.png

02. Ts规范props的类型(PropType):

  1. 使用type定义Title的类型:
type Title = {
value: string;
color: string;
};
  1. props中的属性这样来定义:
props: {
title: {
type: Object as PropType<Title>,
required: true,
},
},
  1. 类型推断正常并提示:

image.png image.png

03. Ts规范computed的写法(规范返回值类型):

  1. 定义制定返回类型的computed:
computed: {
doubleCounter(): number {
return this.counter * 2;
},
},

04. Ts规范methods的写法(规范形参和返回值类型):

createTodo(name: string): Todo {
return { name, id: this.items.length + 1 };
},

05. Ts规范composition api的写法:

  1. 定义属性:
defineProps({
title: {
type: Object as PropType<Title>,
required: true,
},
});
  1. 定义data:
const counter = ref(1);
const items = ref([] as Todo[]);
const todoName = ref("");
  1. 定义计算属性:
const doubleCounter = computed(() => counter.value * 2);
  1. 定义方法:
const createTodo = (name: string): Todo => {
return { name, id: items.value.length + 1 };
};
  1. 使用type规范模块导入:
<script lang="ts" setup>
import { computed, ref } from "vue";
import type { PropType } from "vue";
import type { Todo, Title } from "../types";
</script>

06. Ts规范Vuex4.+的写法:

  1. 安装Vuex4+:yarn add vuex@next --save
  2. 模块扩展(vuex.d.ts):
// 模块扩展:this.$store强类型支持
declare module "@vue/runtime-core" {
interface ComponentCustomProperties {
// 应用泛型约束Store的类型
$store: Store<State>;
}
}
  1. useStore类型化:
    1. 创建一个InjectionKey
export const key: InjectionKey<Store<State>> = Symbol();
  1. 按装store是携带InjectionKey
import store, { key } from "./store";
createApp(App).use(store, key).mount("#app");
  1. composition api中使用
import { useStore } from "vuex";
import { key } from "../store";
const store = useStore(key);
const counter = computed(() => store.state.counter);
  1. useStore(key)再次包装,减少key的导入
export function useStore () {
return baseUseStore(key)
}
  1. 子模块的类型规范:
    1. 定义子模块:
import { State } from "./../index";
import { Module } from "vuex";
import { Todo } from "../../types";
const initialState = {
data: [] as Todo[],
};
// 通过值来推断类型
export type TodoState = typeof initialState;
export default {
namespaced: true,
state: initialState,
mutations: {
initTodo(state, payload: Todo[]) {
state.data = payload;
},
addTodo(state, payload: Todo) {
state.data.push(payload);
},
},
actions: {
initTodo({ commit }) {
setTimeout(() => {
commit("initTodo", [
{
id: 1,
name: "vuex",
},
]);
}, 500);
},
},
} as Module<TodoState, State>;
  1. 挂载到index.ts
import { InjectionKey } from "vue";
import { createStore, Store, useStore as baseUseStore } from "vuex";
import todos, { TodoState } from "./modules/todos";
export type State = {
counter: number;
todos?: TodoState;
};
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore({
state: {
counter: 0,
},
modules: {
todos,
},
});
export function useStore() {
return baseUseStore(key);
}

07. TS规范Vue-Router4的写法:

  1. 安装Vuex4+:yarn add vue-router@4 --save
  2. 扩展路由配置(交叉类型):
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
export type AppRouteRecordRaw = RouteRecordRaw & {
hidden?: boolean;
};
export default createRouter({
history: createWebHashHistory(),
routes: [
{
path: "/",
component: () => import("../view/Home.vue"),
hidden: true,
},
] as AppRouteRecordRaw[],
});

08. Ts规范Axios的写法:

  1. 安装axios:yarn add axios --save
  2. 构建基本结构:
import axios from "axios";
const http = axios.create({
baseURL: import.meta.env.VITI_BASE_URL,
timeout: 5000,
})
export default http;
  1. 通过泛型规范结果的类型:

image.png image.png

09. 支持环境变量的提示

  1. 新建环境变量配置文件.env.development
VITI_BASE_URL = /api
  1. 新建/修改env.d.ts,增加ImportMetaEnv配置:
interface ImportMetaEnv {
VITI_BASE_URL: string;
}
  1. 使用时正常提示:

image.png 由于快捷键冲突,做开发这么多年才改了一下。。。 image.png

  1. 顺便增加一下接口代理:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "https://jsonplaceholder.typicode.com",
changeOrigin: true,
// 重写地址:最终地址不携带api
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
});
// 调用修改
http.get<Todo>("/todos/1");

总结:

以上内容整理自“Young村长”的B站视频,单单去学习Ts语法总是没有在实践中用用学的快,推荐你们多像Young村长学习呀,老铁们。


欢迎关注我的公众号“前端小鑫同学”,原创技术文章第一时间推送。

posted @   前端小鑫同学  阅读(23)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示