目录
一、使用vite搭建项目
二、vite配置
三、安装vue-router
四、安装vuex
五、安装axios
六、Eslint、js-cookie、Nprogress、Path、sass
七、初始化 Element Plus和图标
一、使用vite搭建项目
官网地址:https://cn.vitejs.dev/guide/#scaffolding-your-first-vite-project
我是在cmd中搭建的项目
npm create vite@latest
然后填写项目名称,回车键确定
?选择vue框架模板,上下键选择,回车键确定选中
?选择TypeScript,回车键确定
?到这里还不算结束哦,需要安装依赖npm install,之后再运行npm run dev即可。
这就是运行后的页面啦?
二、vite配置
vite.config.ts
注意:在 ts 模块中加载 node 核心模块需要安装 node 的类型补充模块
npm install --save-dev @types/node
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
port: 5000,
//反向代理
proxy: {
'/api': {
target: 'http://dexon.damai.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
}
},
resolve: {
// 配置路径别名
alias: {
'@': path.resolve(__dirname, 'src')
}
}
})
tsconfig.json中增加baseUrl的配置,来告诉ts别名的路径,否则使用@ts会报错
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": [
"src/*"
]
}
},
}
环境配置
# .env.development
# 开发模式下加载的环境变量
VITE_API_BASEURL=http://a.com
# .env.production
# 生产模式下加载的环境变量
VITE_API_BASEURL=http://b.com
// src\utils\request.ts
const request = axios.create({
baseURL: import.meta.env.VITE_API_BASEURL
})
三、安装vue-router
官网地址:https://router.vuejs.org/zh/installation.html
?下载路由
npm install vue-router@4
下载完成后,创建src/router/index.ts
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
// 静态路由
const routes: Array<RouteRecordRaw> = [
];
// 动态路由
const asyncRouter = [
]
const router = createRouter({
history: createWebHashHistory(),
routes,
// routes: [...routes, ...asyncRouter],
});
export default router;
一定不要忘记在mian.ts中引入
import router from './router/index'
createApp(App).use(router).mount('#app')
四、安装vuex
官网地址:https://vuex.vuejs.org/zh/installation.html
npm install vuex@next --save
创建src/store文件
modules是模块化,index.ts是组装模块并导出store的地方,然后封装了types.ts,types.ts是对值所具有的结构进行类型检查
index.ts(注释掉的地方就是模块引入的地方)
import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'
import RootStateTypes, { AllStateTypes } from './types'
// import user from "./modules/user/index"
// import app from "./modules/app/index"
// import permission from "./modules/permission/index"
export const store = createStore<RootStateTypes>({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {
// app,
// user,
// permission,
}
})
export const key: InjectionKey<Store<RootStateTypes>> = Symbol('vue-store')
export function useStore<T = AllStateTypes>() {
return baseUseStore<T>(key)
}
types.ts(注释掉的地方就是模块引入的地方)
// import app from './modules/app/types'
// import user from './modules/user/types'
// import permission from './modules/permission/types'
export default interface RootStateTypes {
}
export interface AllStateTypes extends RootStateTypes {
// app: app,
// user: user,
// permission: permission,
}
modules中就举例user模块
modules/user/type.ts
export default interface userState {
token: any,
info: object,
name: any,
avatar: any
}
modules/user/index.ts
import { loginApi, getInfoApi, loginOutApi } from '@/api/user'
import { Module } from 'vuex'
import RootStateTypes from '../../types'
import sidebar from './types'
// import { resetRouter } from '@/router'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
import axios from 'axios'
const getDefaultState = () => {
return {
token: getToken(), // 登录token
info: {}, // 用户信息
name: '',//用户名称
avatar: ''//用户头像
}
}
const sidebar: Module<sidebar, RootStateTypes> = {
namespaced: true,
state: getDefaultState(),
getters: {
token: (state: any) => state.token,
name: (state: any) => state.name,
avatar: (state: any) => state.avatar,
info: (state: any) => state.info,
},
mutations: {
// 清除state
RESET_STATE: (state: sidebar) => {
Object.assign(state, getDefaultState())
},
tokenChange(state: sidebar, token: string) {
state.token = token
},
infoChange(state: sidebar, info: object) {
state.info = info
},
nameChange(state: sidebar, name: object) {
state.name = name
},
avaterChange(state: sidebar, avatar: object) {
state.avatar = avatar
},
},
actions: {
// 登录
async login({ commit, dispatch }: any, userInfo: any) {
return new Promise((resolve, reject) => {
loginApi(userInfo).then(response => {
// console.log(response);
// 200登录成功 500 登录失败(账号密码不对)
const { data } = response
commit('tokenChange', data.token)
setToken(data.token)
setTime() // 存当前时间
resolve(null)
}).catch(error => {
reject(error.msg)
})
})
},
// 获取登录后信息
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfoApi({ token: state.token })
.then(res => {
const { data } = res
if (!data) {
return reject('Verification failed, please Login again.')
}
console.log(data, '登录信息返回的数据')
const { name, avatar } = data
commit('infoChange', data)
commit('avaterChange', avatar)
commit('nameChange', name)
resolve(data)
}).catch(error => {
reject(error.msg)
})
})
},
//退出登录
loginOut({ commit, state }: any) {
return new Promise<void>((resolve, reject) => {
loginOutApi(state.token).then(() => {
removeToken() // 去除token
// resetRouter() //重置路由
commit('RESET_STATE') //清除state
resolve()
}).catch(error => {
reject(error)
})
})
},
// 去除token
resetToken({ commit }) {
return new Promise<void>(resolve => {
removeToken()
// resetRouter()
commit('RESET_STATE')
location.reload() // 刷新
resolve()
})
}
},
}
export default sidebar
最后在main.ts引入store
import router from './router/index'
import { store } from "./store";
createApp(App).use(store).use(router).mount('#app')
五、安装axios
官网地址:http://www.axios-js.com/zh-cn/docs/
npm install axios
在所需页面中使用import引入即可,封装请求模块中使用,比如请求拦截器等中使用
六、Eslint、js-cookie、Nprogress、Path、sass
都是在所需页面中引入即可使用
Eslint——代码校验
npm install eslint --save-dev
npm install @typescript-eslint/parser
npm install @typescript-eslint/eslint-plugin
?创建.eslintrc.js文件
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
'vue/setup-compiler-macros': true
},
globals: {
defineProps: 'readonly',
defineEmits: 'readonly',
defineExpose: 'readonly'
},
parser: 'vue-eslint-parser',
extends: [
'eslint:recommended',
'plugin:vue/vue3-essential',
'plugin:@typescript-eslint/recommended'
],
parserOptions: {
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: ['vue', '@typescript-eslint'],
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-empty-function': 'off', // 关闭空方法检查
'@typescript-eslint/no-explicit-any': 'off', // 关闭any类型的警告
'vue/no-v-model-argument': 'off',
'@typescript-eslint/no-var-requires': 0,
}
};
js-cookie——像是存储登录后的信息就可使用
npm i --save-dev @types/js-cookie
npm install js-cookie --save
Nprogress——在路由跳转前中使用
npm install --save nprogress
npm i --save-dev @types/nprogress
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
Path——vite.config.ts
npm install @types/node --save-dev
sass——css样式管理
npm install -D sass
七、初始化 Element Plus和图标
npm install element-plus --save
npm install @element-plus/icons
mian.ts
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'element-plus/dist/index.css'
import * as icons from '@element-plus/icons'
const app = createApp(App)
app.use(ElementPlus).mount('#app')
// 图标
for (const [key, component] of Object.entries(icons)) {
app.component(key, component)
}
|