vue3 + vite + ts + antdv 搭建后臺管理基礎框架

文章封面.jpg

最近公司官網(wǎng)需要一個后臺管理系統(tǒng),一直在看vue3,但是都沒有在實際項目中使用過,正好就借此機會來踩踩坑。

點擊這里查看源碼

環(huán)境準備

  • Node.js v14.9.0
  • npm v6.14.8
  • vscode

搭建 Vite 項目

Vite中文網(wǎng) (vitejs.cn)
Vite 需要 Node.js 版本 >= 12.0.0

// 安裝vue-ts 模板
npm init @vitejs/app vue3-template --template vue-ts

npm run dev  // 啟動開發(fā)服務器
npm run build // 為生產(chǎn)環(huán)境構(gòu)建產(chǎn)物
npm run serve // 本地預覽生產(chǎn)構(gòu)建產(chǎn)物

啟動項目的第一感覺就是一個字 ,還沒反應過來就已經(jīng)跑起來了

安裝 vue-router

起步 | Vue Router (vuejs.org)

npm install vue-router@4
  1. 首先在 src 目錄下創(chuàng)建 router 文件夾, 為了項目后期更好的可讀性和維護,這里將路由進行模塊化管理, 對開發(fā)和調(diào)試都會有很大幫助,目錄結(jié)構(gòu)如下:

    image.png

  2. index.ts文件

import { createRouter, createWebHashHistory } from "vue-router"

import Common from "./modules/common"
import Movie from "./modules/movie"

const routes = [
  Movie,
  ...Common
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router
  1. common.ts 文件
/**
 * @description 公共的一些路由,不屬于功能模塊的都放這里統(tǒng)一管理
 * @author 逗叔 */

import Layout from "@/layout/index.vue";

//首頁路由
const Home = {
  path: "/",
  component: Layout,
  meta: {
    title: "首頁"
  },
  redirect: { name: "Home" },
  children: [
    {
      path: "/home",
      name: "Home",
      component: () => import("@/views/home/index.vue"),
      meta: {
        title: "首頁"
      }
    }
  ]
};

//登錄、快速登錄、選擇應用
const Login = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
    meta: {
      title: "登錄"
    }
  }
];

//其他路由、無權(quán)限、日志、404
const Others = [
  {
    path: "/401",
    name: "Error401",
    component: () => import("@/views/error-page/401.vue"),
    meta: {
      title: "無權(quán)限"
    }
  },
  {
    path: "/404",
    name: "Error404",
    component: () => import("@/views/error-page/404.vue"),
    meta: {
      title: "404"
    }
  },
  {
    path: "/500",
    name: "Error500",
    component: () => import("@/views/error-page/500.vue"),
    meta: {
      title: "500"
    }
  },
  {
    path: "/:pathMatch(.*)",
    redirect: '/404'
  }
];

let Common = [Home, ...Login, ...Others];

export default Common;

這里需要注意的是 * 通配符 需要改為 /:pathMatch(.*)

  1. 修改 main.ts 文件

    image.png

  2. 使用

import { useRouter } from "vue-router";
setup() {
    const router = useRouter();
    router.push({ name: "Home" });
}

安裝 Vuex

安裝 | Vuex (vuejs.org)

npm install vuex@next --save
  1. src 目錄下創(chuàng)建 store 文件夾

    image.png

  2. index.ts 文件

import { InjectionKey } from 'vue'
import { createStore, Store } from 'vuex'
import getters from './getters'

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

import common from './modules/common'

// 創(chuàng)建一個新的 store 實例
export const store = createStore({
  modules: {
    common
  },
  getters
})
  1. getters.ts 文件
const getters = {
  token: (state:any) => state.common.token
}

export default getters
  1. modules/common.ts 文件
export default {
  namespaced: true,
  state: {
    token: ''
  },
  mutations: {
    //存儲token
    setToken(state: { token: string }, token: string) {
      state.token = token
      localStorage.token = token
    }
  },
  getters: {
    //獲取token方法
    getToken(state: { token: string | null }) {
      if (!state.token) {
        state.token = localStorage.getItem('token')
      }
      return state.token
    }
  }
}
  1. 修改 main.ts 文件

    image.png

  2. 使用

import { useStore } from 'vuex'
import { key } from '../../store'
setup() {
    const store = useStore(key)
    store.commit("common/setToken",res.data)
}

這里需要注意 useStore 要傳一個 key,不然獲取不到的 store,網(wǎng)上的教程一大堆都是獲取不到的

安裝 Antdv

起步 | Ant Design Vue (antdv.com)

npm i --save ant-design-vue@next

按需加載組件

  1. 安裝 vite-plugin-style-import
npm i vite-plugin-style-import -D
  1. 修改 vite.config.ts 文件
    image.png
 styleImport({
      libs: [{
        libraryName: 'ant-design-vue',
        esModule: true,
        resolveStyle: (name) => {
          return `ant-design-vue/es/${name}/style/css`;
        },
      }]
    })
  1. src 目錄下創(chuàng)建 plugins 文件夾
    image.png

ant-design-vue/index.ts 內(nèi)容

import type { App } from "vue"

import { Layout, Menu, Breadcrumb, Form, Result, Button, Input, Checkbox, message } from 'ant-design-vue';

const antdComponents = [
  Layout,
  Menu,
  Breadcrumb,
  Form,
  Result,
  Button,
  Input,
  Checkbox,
]

// 應用組件
export function useAntd(app: App) {
  // 循環(huán)應用
  antdComponents.forEach(com => {
    app.use(com)
  })
  app.config.globalProperties.$message = message;
}
  1. 修改 main.ts 文件
    image.png

封裝 Axios

npm install axios
  1. src 目錄下創(chuàng)建 utils 文件夾 和 api 文件夾

    image.png

  2. utils/request.ts文件

/**axios封裝
 * 請求攔截、相應攔截、錯誤統(tǒng)一處理
 */
import axios from "axios";
import { message } from "ant-design-vue";

// 創(chuàng)建axios實例
const instance = axios.create({
  // baseURL:"",
  // timeout: 10 * 1000,
  // withCredentials: true,
  headers: {
    "Content-Type": "application/json"
  }
});

// 請求攔截器
instance.interceptors.request.use(
  config => {
    // 全局添加token
    // config.headers["Authorization"] = token;
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 響應攔截器
instance.interceptors.response.use(
  response => {
    const data = response.data;
    // code 是后端返回的業(yè)務狀態(tài)碼 {code:0,data:{},message:"成功"}
    if (data.code !== 0) {
      message.error(data.message)
      return Promise.reject(new Error(data.message || "Error"));
    } else {
      return data;
    }
  },
  error => {
    const { response } = error;
    switch (response.status) {
      //404 資源不存在
      case 404:
        message.error("網(wǎng)絡請求不存在");
        break;
      // 系統(tǒng)錯誤
      case 500:
        message.error(response.data.errorMessage || "服務器異常,請稍后重試")
        break;
      // 其他錯誤,直接拋出錯誤提示
      default:
        message.error(response.data.errorMessage || "請求出現(xiàn)未知錯誤,請稍后重試")
    }
    return Promise.reject(error);
  }
);

export default instance;

  1. api/base.ts
/**
 * 接口域名的管理
 * 解決多域名接口的情況
 */
const base = {
  baseUrl: "/api/vue3-template",
  //繼續(xù)寫其他域名的接口
};

export default base;
  1. api/common.ts
/**
 * 測試接口列表
 */

import base from "./base"; // 導入接口域名列表
import axios from "../utils/request"; // 導入request中創(chuàng)建的axios實例

const common = {
  /**
   * 登錄
   * @param params 
   */
  login(params: any) {
    return axios.post(`${base.baseUrl}/login`, params)
  }
};

export default common;

  1. api/index.ts
/**
 * api接口的統(tǒng)一出口
 */

// 測試接口
import common from "./common";

export default {
  common,
};
  1. api掛載到全局
    image.png
import Api from "./api"
//全局掛載 Api接口
app.config.globalProperties.$api = Api;
  1. 使用
import { reactive, ref, defineComponent, toRaw, getCurrentInstance } from "vue";
// @ts-ignore
const { proxy } = getCurrentInstance();
const api = proxy.$api;
// 調(diào)用登錄接口
api.common.login(toRaw(loginForm))
          .then((res: any) => {
              message.success("登錄成功");
              store.commit("common/setToken",res.data)
              router.push({ name: "Home" });
            })
            .catch((err: any) => {
              message.error("登錄失敗");
            });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容