将Ts往Vue3中再整合一下

我心飞翔 分类:vue

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

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

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

使用type定义Todo的类型:

type Todo = {
  id: number;
  name: string;
};

data中的属性这样来定义:

data() {
 return {
   items: [] as Todo[],
 };
},

类型推断正常并提示:

将Ts往Vue3中再整合一下

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

使用type定义Title的类型:

type Title = {
  value: string;
  color: string;
};

props中的属性这样来定义:

props: {
 title: {
   type: Object as PropType<Title>,
   required: true,
 },
},

类型推断正常并提示:

将Ts往Vue3中再整合一下
将Ts往Vue3中再整合一下

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

定义制定返回类型的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的写法:

定义属性:

defineProps({
  title: {
 type: Object as PropType<Title>,
 required: true,
  },
});

定义data:

const counter = ref(1);
const items = ref([] as Todo[]);
const todoName = ref("");

定义计算属性:

const doubleCounter = computed(() => counter.value * 2);

定义方法:

const createTodo = (name: string): Todo => {
  return { name, id: items.value.length + 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.+的写法:

安装Vuex4+:yarn add vuex@next --save

模块扩展(vuex.d.ts):

// 模块扩展:this.$store强类型支持
declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
 // 应用泛型约束Store的类型
 $store: Store<State>;
  }
}

useStore类型化:

创建一个InjectionKey

export const key: InjectionKey<Store<State>> = Symbol();

按装store是携带InjectionKey

import store, { key } from "./store";
createApp(App).use(store,  key).mount("#app");

composition api中使用

import { useStore } from "vuex";
import { key } from "../store";
const store = useStore(key);
const counter = computed(() => store.state.counter);

useStore(key)再次包装,减少key的导入

export function useStore () {
  return baseUseStore(key)
}

子模块的类型规范:

  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>;

2. 挂载到index.ts

```typescript
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`

1. 构建基本结构:

import axios from "axios";

 const http = axios.create({
    baseURL: import.meta.env.VITI_BASE_URL,
    timeout: 5000,
})

export default http;
  1. 通过泛型规范结果的类型:
将Ts往Vue3中再整合一下
将Ts往Vue3中再整合一下

09. 支持环境变量的提示

新建环境变量配置文件.env.development

VITI_BASE_URL = /api

新建/修改env.d.ts,增加ImportMetaEnv配置:

interface ImportMetaEnv {
  VITI_BASE_URL: string;
}

使用时正常提示:

将Ts往Vue3中再整合一下

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

将Ts往Vue3中再整合一下
  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村长学习呀,老铁们。

回复

我来回复
  • 暂无回复内容