This is the 11th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

# VUe3 + TS Project Setup and Packaging (Part 1)

Configuration request. Ts

/** * Axios secondary encapsulation * @auther he xiaosheng. * @time 2021/08/05 05:24 */ import axios from 'axios' // Import axios from '.. Config import {ElMessage} from 'element-plus' // Import router from '.. // import {storage} from './storage'; Const TOKEN_INVALID = 'Token authentication failed, please log in again 'const NETWORK_ERROR =' Network request is abnormal, please try again later '// Create axios instance object, Add global configuration const Service = axios.create({// Initial configuration request header request mockAPI when mock environment, otherwise request formal API baseURL: config.mock? Config. mockApi: config.baseApi, // interface duration is 8 seconds, otherwise timeout: 8000}) / / request intercept service. The interceptors. Request. Use ((the req) = > {/ / to-do / / get request head const headers = the req. Headers / / access token Because the typescript is, so to do reject assignment const {token = ""} = storage. Get (' the userInfo) | | {} / / to the backend definition of a request header value used to resolve the token identity token if (! Headers.Authorization = 'xiaohe '+ token // Return request header return req}) // Response interception Service. The interceptors. Response. Use ((res) = > {/ / backend return code, Data and prompt const {code, data, MSG} = res.data if(code == 200) return data else if(code === 50001) {// Token authentication failed elmessage. error(TOKEN_INVALID) // After giving the status code 5001 and giving the user a certain amount of time to respond, SetTimeout (() => {router-.push ('/login')}, 15000) return Promise. Reject (TOKEN_INVALID) / / throw an exception} else {/ / throw out abnormal ElMessage server. The error (MSG | | NETWORK_ERROR) return Promise. Reject (MSG | | NETWORK_ERROR)}}) / * * * @ param {*} configuration options request * / function request (options: any) { options.method = options.method || 'get' if(options.method.toLowerCase() === 'get') options.params = options.data  if(typeof options.mock ! = 'undefined') config.mock = options.mock if(config.env === 'prod') service.defaults.baseURL = config.baseApi else service.defaults.baseURL = config.mock ? config.mockApi : Config.baseapi return service(options)} ForEach (item => {request[item] = (URL: string, data: any, options: string[]) => { return request({ url, data, method: item, ... Options})}}) // Throw the request export default requestCopy the code

Enclosed storage. Ts

Storage and sessionStorage are used for cache encapsulation

/** * encapsulation operation localstorage localstorage method * @auther he young life. * @date 2021/06/28 */ export const storage = {key: string, value: Any) {window. LocalStorage. SetItem (key, JSON stringify (value))}, / / remove the data get < T > (key: string) { const value = window.localStorage.getItem(key) if (value && value ! = "undefined" && value ! = "null") return <T> json. parse(value) else return "{}"}, // delete data string) { window.localStorage.removeItem(key) } }; */ export const sessionStorage = {// store set(key: string, value: Any) {window. The sessionStorage. SetItem (key, JSON stringify (value))}, / / remove the data get < T > (key: string) { const value = window.sessionStorage.getItem(key); if (value && value ! = "undefined" && value ! = "null") return json. parse(value) return null}, remove(key: string) { window.sessionStorage.removeItem(key) } }Copy the code

Configure config. Ts

Create the config folder under the SRC directory, and then create index.ts to configure the basic configuration parameters of the request and to distinguish between production and development environments

Export interface IConfig {env: string : Boolean // Mock data title: string // project title baseApi? : string // API request address mockApi? : string // mock address} const dev: IConfig = {env: "development", mock: false, title: "development", baseApi: "/ API ", // local API request address, note: If you are using a proxy, set this to '/' mockApi: "https://www.fastmock.site/mock/4f8c864d98d32e623e4a452a904ca70b/api" } const prod: IConfig = { env: "Production", mock: false, the title: "production", baseApi: "https://www.baidu.com/api", / / formal API request address mockApi: 'xxx' } export const config: IConfig = import.meta.env.MODE == 'development' ? dev : prodCopy the code

Configuring API Encapsulation

In the SRC directory, create the API folder and generate the user.ts file to store the interfaces such as login, registration, and forgetting the password

import request from '.. /utils/request' interface userState { username: string password: String} export default {/** * login interface * @param {string} username username * @param {string} password user password */ login(data:  userState ) { return request({ url: '/users/login', method: 'post', data }) } }Copy the code

Configure the router and route guard

Create index.ts and router-config. ts in the SRC folder

  • Route guard configuration
import { createRouter, createWebHistory } from "vue-router" import { constantRouterMap } from "./router.config" import { useDocumentTitle } from "@/hooks/useDocumentTitle" import store from "@/store" const router = createRouter({ history: CreateWebHistory (import.meta.env.base_URL), // When the back/forward button is pressed, ScrollBehavior (to, from, savedPosition) {if (savedPosition) return savedPosition else return {top: 0}}, routes: constantRouterMap}) // Routes start to enter router.beforeEach((to: any, from: any, next) => { useDocumentTitle(to.meta.title) next() return false }) router.afterEach((to, from, Next) => {// save url}) export default RouterCopy the code
  • The routing configuration
import { RouteRecordRaw } from "./vue-router" import Layout from '@/layout/index.vue' export const constantRouterMap: Array<RouteRecordRaw> = [ { path: '/login', name: 'login', component: () => import('@/views/login/login.vue'), meta: {title: 'login'}, hidden: true}, {path: '/', name: '/', component: Layout, redirect: '/index', meta: {title: 'login'}, hidden: true}, {path: '/', name: '/', component: Layout, redirect: '/index', meta: {title: }, children: [{path: '/index', name: 'index', component: () = > import (' @ / views/index/index. The vue '), meta: {title: 'blog' icon: 'el - icon - link'}}}, {path: '/ 404' name: 'page404', component: () => import('@/views/404.vue'), meta: { title: '404' }, hidden: true }, { path: '/:catchAll(.*)', redirect: '/404', hidden: true } ]Copy the code

The main js configuration

Finally, configure it in main.js

import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import svgIcon from './icons/index.vue' import { storage, sessionStorage } from './utils/storage' import ElementPlus from 'element-plus' import 'element-plus/lib/ theme-Chalk /index.css' // Import global style import "./styles/base.css" import "./styles/reset.css" const app = CreateApp (App) App. Config. GlobalProperties. Storage = storage / / global mount cache method App config. GlobalProperties. SessionStorage = App.use (router).use(store).use(ElementPlus).component(' SVG-icon ', svgIcon) .mount('#app')Copy the code

The last

Public number: xiao He growth, The Buddha department more text, are their own once stepped on the pit or is learned

Interested partners welcome to pay attention to me, I am: He young life. Everybody progress duck together