文章封面.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
npm install vue-router@4
-
首先在
src
目錄下創(chuàng)建router
文件夾, 為了項目后期更好的可讀性和維護,這里將路由進行模塊化管理, 對開發(fā)和調(diào)試都會有很大幫助,目錄結(jié)構(gòu)如下:
image.png 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
- 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(.*)
-
修改
main.ts
文件
image.png 使用
import { useRouter } from "vue-router";
setup() {
const router = useRouter();
router.push({ name: "Home" });
}
安裝 Vuex
npm install vuex@next --save
-
在
src
目錄下創(chuàng)建store
文件夾
image.png 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
})
-
getters.ts
文件
const getters = {
token: (state:any) => state.common.token
}
export default getters
-
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
}
}
}
-
修改
main.ts
文件
image.png 使用
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
按需加載組件
- 安裝
vite-plugin-style-import
npm i vite-plugin-style-import -D
- 修改
vite.config.ts
文件
image.png
styleImport({
libs: [{
libraryName: 'ant-design-vue',
esModule: true,
resolveStyle: (name) => {
return `ant-design-vue/es/${name}/style/css`;
},
}]
})
- 在
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;
}
- 修改
main.ts
文件
image.png
封裝 Axios
npm install axios
-
在
src
目錄下創(chuàng)建utils
文件夾 和api
文件夾
image.png 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;
api/base.ts
/**
* 接口域名的管理
* 解決多域名接口的情況
*/
const base = {
baseUrl: "/api/vue3-template",
//繼續(xù)寫其他域名的接口
};
export default base;
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;
api/index.ts
/**
* api接口的統(tǒng)一出口
*/
// 測試接口
import common from "./common";
export default {
common,
};
- 把
api
掛載到全局
image.png
import Api from "./api"
//全局掛載 Api接口
app.config.globalProperties.$api = Api;
- 使用
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("登錄失敗");
});