How to reconstruct the vue2 project into vue3 "backend management system"


Preface

First of all, we need to know that vue3 is based on vue2 with some changes but not much. Basically, just copy the backend management system of vue2 and rewrite the project.


1. Basic configuration

Speaking of login pages. The so-called login means that there must be a reference object. If you enter your account or password and meet the standard of the reference object, the next step will be taken. Otherwise it will not jump. Login also requires regular verification and standardized input content. The input content must also be passed to the server.

Create vue3 file

view-cli

 
● 安装并执行 create-vue:npm init vue@latest
它是 Vue 官方的项目脚手架工具
● 选择项目功能
除了第一项的项目名字外,其他可以暂时默认回撤或者选择 No
✔ Project name: … <your-project-name> 
✔ Add TypeScript? … No / Yes 
✔ Add JSX Support? … No / Yes 
✔ Add Vue Router for Single Page Application development? … No / Yes 
✔ Add Pinia for state management? … No / Yes 
✔ Add Vitest for Unit testing? … No / Yes 
✔ Add Cypress for both Unit and End-to-End testing? … No / Yes 
✔ Add ESLint for code quality? … No / Yes 
✔ Add Prettier for code formatting? … No / Yes 

Scaffolding project in ./<your-project-name>... 
Done.
切换到项目目录:cd <your-project-name>
安装项目依赖:npm install
启动开发服务器:npm run dev
将应用发布到生产环境:npm run build


quickly

使用 vite 体验更快速
$ npm init vite-app <project-name> 
$ cd <project-name> 
$ npm install 
$ npm run dev 

#yarn
$ yarn create vite-app <project-name> 
$ cd <project-name> 
$ yarn 
$ yarn dev 

What plug-ins are needed and what plug-ins are required?

package.json


//傻瓜式安装 npm i
{
  "name": "vue3-project",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "axios": "^1.3.3",
    "echarts": "^4.9.0",
    "element-plus": "^2.2.30",
    "path": "^0.12.7",
    "qs": "^6.11.0",
    "vite-aliases": "^0.10.0",
    "vue": "^3.0.4",
    "vue-router": "^4.1.6"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.0.0",
    "font-awesome": "^4.7.0",
    "node-sass": "^6.0.1",
    "sass": "^1.58.1",
    "sass-loader": "^10.4.1",
    "vite": "^4.1.0"
  }
}

Since the package is configured, it needs to be introduced in main.js. This does not need to be considered because you install it and use it. Since you want to use it, you must reference it.

main.js

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

import axios from 'axios'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 国际版(翻译)
import local from 'element-plus/es/locale/lang/zh-cn'
import router from './router'

import 'font-awesome/css/font-awesome.min.css'

import echarts from 'echarts'

import service from './api/service'

const app = createApp(App);
app.use(ElementPlus, { local })
app.use(router)
app.config.globalProperties.$https = axios
app.config.globalProperties.service = service
app.config.globalProperties.$echarts = echarts
app.mount('#app')

vue3 cannot use the absolute path "@" symbol. We need to find a way to solve this problem. We can configure the @ symbol rules in vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { ViteAliases } from "./node_modules/vite-aliases"
// https://vitejs.dev/config/
export default defineConfig({

//配置 @ 适配
    plugins: [
        vue(),
        ViteAliases({ prefix: "@" })
    ],
    server: {
        proxy: {
            '/api': {
                target: 'http://1.116.64.64:5004/api2',
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ''),
            }
        }
    }
})



Set the token again so that the login page has a reference standard.

setToken.js under the utils folder

/*
 * @Author: error: git config user.name && git config user.email & please set dead value or install git
 * @Date: 2022-11-25 11:07:56
 * @LastEditors: error: git config user.name && git config user.email & please set dead value or install git
 * @LastEditTime: 2023-01-01 15:49:12
 * @FilePath: \project-one\src\utils\setToken.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 设置 token 值
export function setToken(tokenKey, tokenValue) {
    return localStorage.setItem(tokenKey,tokenValue)
}
// 获取 token 值
export function getToken(tokenKey) {
    return localStorage.getItem(tokenKey)
}
// 删除 token 值
export function removeToken(tokenKey) {
    return localStorage.removeItem(tokenKey)
}

Then find a way to submit the value entered by inpt to verify the token.

Encapsulate the API

Under the api file, first create an api interceptor to observe the passed data.

service.js

import axios from 'axios'
// 引入 token 信息
import { getToken } from "../utils/setToken";
import { ElMessage } from 'element-plus';

const service = axios.create({
    // baseURL会自动加在接口地址上
    baseURL: "/api",
    // timeout 规定的请求时间
    timeout: 5000 // 指定请求的超时毫秒数,如果请求超过这个时间,那么请求就会中断。
})

// 添加请求拦截器
service.interceptors.request.use((config) => {
    // 在发送请求前做些什么
    // 获取并设置token
    // console.log(getToken('token'))
    // 在请求报文的头部,添加 token
    config.headers['token'] = getToken('token')
    return config
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use((response) => {
    // 对响应数据做些什么
    // console.log(response)
    // 对响应的数据,同一做出判断
    let { status, message } = response.data
    if (status !== 200) {
        ElMessage({ message: message || 'error', type: 'warning' })
    }
    return response
}, (error) => {
    // 对响应错误做点什么
    return Promise.reject(error)
})

export default service

Then configure the api interface
api.js

import service from "./service";
import qs from 'qs'

// 登录接口
export function login(data) {
    return service({
        method: 'post',
        url: `/login`,
        data
    })
}

// 学生列表接口
export function student(params) {
    return service({
        method: 'get',
        url: '/students',
        params
    })
}

// 学生列表删除接口
export function studentDel(id) {
    return service({
        method: 'delete',
        url: `/students/${id}`,
    })
}

// 信息列表的查询接口
export function getInfo() {
    return service({
        method: 'get',
        url: `/info`,
    })
}
// 信息列表新增修改的接口
export function info(type,data) {
    // qs.stringify 将对象解析为url; qs.parse() 将url转换成对象; 类似于 JSON.Stringify()
    data = qs.stringify(data)
    let obj = {method:type,url:'/info',data}
    return service(obj)
}

// 信息列表的删除
export function infoDel(id) {
    return service({
        method: 'delete',
        url: `/info/${id}`,
    })
}

// 数据概览接口
export function dataView() {
    return service({
        method: 'get',
        url:'/dataview'
    })
}

// 旅游地图接口
export function travel() {
    return service({
        method: 'get',
        url:'/travel'
    })
}

Next is the login page

Copy the vue2 project and
the link is below

"Backstage Management System" (Part 1)

"Backstage Management System" (Part 2)

"Backstage Management System" (Part 2)

Summarize

How to write the vue3 format can be changed as long as the combination of options can be used flexibly

Guess you like

Origin blog.csdn.net/www61621/article/details/129063059