README.md 9.0 KB
Newer Older
1
## 官网地址
2 3 4 5 6

- vue3: https://v3.cn.vuejs.org/guide/introduction.html

- vite2: https://cn.vitejs.dev/guide/

7 8 9
- vuex4:https://next.vuex.vuejs.org/zh/index.html

- vue-router4 : https://next.router.vuejs.org/zh/introduction.html
10

有来技术 已提交
11 12
- element-plus: https://element-plus.gitee.io/zh-CN/

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29


## Vite项目构建

Vite是一种新型前端构建工具,能够显著提升前端开发体验。

[Vite 官方中文文档](https://cn.vitejs.dev/ )

```shell
npm init vite@latest vue3-element-admin --template vue-ts
cd vue3-element-admin
npm install
npm run dev
```

访问本地: http://localhost:3000

30
## vue-router
31 32 33 34 35

```text
npm install vue-router@next
```

.  
有来技术 已提交
36
src 下创建 router/interface.ts
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

```typescript
import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'
import HelloWord from '../components/HelloWorld.vue'

const routes: Array<RouteRecordRaw> = [
    {
        path: '',
        redirect: (_) => {
            return {path: '/home'}
        }
    },
    {
        path: '/home',
        name: 'HelloWord',
        component: HelloWord
    }
]

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

export default router
```

**参考文档:**

- [路由的 hash 模式和 history 模式的区别](https://www.cnblogs.com/GGbondLearn/p/12239651.html)

68
## vuex
69 70 71 72 73

```shell
npm install vuex@next
```

.  
有来技术 已提交
74
src 下创建 store/interface.ts
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

```typescript
import {InjectionKey} from 'vue'
import {createStore, Store} from 'vuex'

export interface State {
    count: number
}

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


export const store = createStore<State>({
    state() {
        return {
            count: 0
        }
    },
    mutations: {
        increment(state: { count: number }) {
            state.count++
        }
    }
})
```

**参考文档:**

- [Vue3 的 InjectionKey 解决提供者和消费者同步注入值的类型](https://www.jianshu.com/p/7064c5f8f143)



## element-plus

```shell
npm install element-plus
```

## main.ts

```typescript
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";
import {store,key} from './store'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app=createApp(App)
app
    .use(router)
    .use(store,key)
    .use(ElementPlus)
    .mount('#app')
```



## Vite 设置路径别名

#### 安装 @types/node

```shell
npm install --save-dev @types/node
```

或者简写

```shell
 npm i -D @types/node
```

#### vite.config.ts

```typescript
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
// 在 ts 模块中加载 node 核心模块需要安装 node 的类型补充模块: npm i -D @types/node
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [vue()],
    resolve: {
        // Vite2设置别名路径方式一
        /**
         alias:{

           "/@":path.resolve("./src"),
         },
         **/

        // Vite2设置别名路径方式二
        alias: [
            {
                find: "@",
                replacement: path.resolve("./src")
            },
            {
                find: "@image",
                replacement: path.resolve("./src/assets/images")
            },
            {
                find: "@router",
                replacement: path.resolve("./src/router")
            },
            {
                find: "@store",
                replacement: path.resolve("./src/store")
            },
            {
                find: "@api",
                replacement: path.resolve("./src/api")
            }
        ]
    }
})

```

#### tsconfig.json

TS配置别名路径,否则使用别名路径会报错,下面关键配置 `baseUrl``paths``include`

```json
{
  "compilerOptions": {
	...
    "baseUrl": "./",
    "paths": {
      "@": ["src"],
207
      "@*": ["src/*"]
208 209 210 211 212 213 214 215 216 217 218
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

```



## Vite 环境变量配置

219
**官方环境变量配置文档:** https://cn.vitejs.dev/guide/env-and-mode.html
220

有来技术 已提交
221
#### 配置文件
222

有来技术 已提交
223
在项目根目录分别添加 `开发环境配置``生产环境配置``模拟环境配置`文件
224

有来技术 已提交
225
开发环境配置:`.env.development`
226

有来技术 已提交
227 228
```properties
# 开发环境变量 注意:变量必须以 VITE_ 为前缀才能暴露给外部读取
229 230 231 232
VITE_APP_TITLE = '管理系统'
VITE_APP_PORT = 3000
VITE_APP_BASE_API = '/dev-api'
```
233 234


有来技术 已提交
235
生产环境配置:`.env.production`
236 237 238

```properties
# 生产环境变量
239 240 241
VITE_APP_TITLE = '管理系统'
VITE_APP_PORT = 3000
VITE_APP_BASE_API = '/prod-api'
242 243 244
```


有来技术 已提交
245
模拟环境配置:`.env.staging`
246 247 248

```properties
# 模拟环境变量
249 250 251
VITE_APP_TITLE = '管理系统'
VITE_APP_PORT = 3000
VITE_APP_BASE_API = '/stage-api'
252 253
```

254 255 256
#### 环境变量智能提示

`src/env.d.ts` 添加以下配置
257

258 259 260 261 262 263 264 265
```typescript
// 环境变量智能提示
interface ImportMetaEnv {
    VITE_APP_TITLE: string,
    VITE_APP_PORT: string,
    VITE_APP_BASE_API: string
}
```
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

## 生产打包配置

#### package.json

```json
"scripts": {
    "dev": "vite serve --mode development",
    "build:prod": "vue-tsc --noEmit && vite build --mode production",
    "serve": "vite preview"
}
```

#### tsconfig.json

```json
{
  "compilerOptions": {
  	...
    "skipLibCheck": true  // element-plus 生产打包报错,通过此配置修改 TS 不对第三方依赖类型检查
  }
}

```

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
执行 `npm run build:prod` 命令打包,生成的打包文件在项目根目录 `dist` 目录下



##  axios 封装

#### 安装axios

```
 npm i axios
```

#### 缓存工具类

**src/utils/storage.ts**

```typescript
/**
 * window.localStorage 浏览器永久缓存
 */
export const Local = {
	// 设置永久缓存
	set(key: string, val: any) {
		window.localStorage.setItem(key, JSON.stringify(val));
	},
	// 获取永久缓存
	get(key: string) {
		let json: any = window.localStorage.getItem(key);
		return JSON.parse(json);
	},
	// 移除永久缓存
	remove(key: string) {
		window.localStorage.removeItem(key);
	},
	// 移除全部永久缓存
	clear() {
		window.localStorage.clear();
	},
};

/**
 * window.sessionStorage 浏览器临时缓存
 */
export const Session = {
	// 设置临时缓存
	set(key: string, val: any) {
		window.sessionStorage.setItem(key, JSON.stringify(val));
	},
	// 获取临时缓存
	get(key: string) {
		let json: any = window.sessionStorage.getItem(key);
		return JSON.parse(json);
	},
	// 移除临时缓存
	remove(key: string) {
		window.sessionStorage.removeItem(key);
	},
	// 移除全部临时缓存
	clear() {
		window.sessionStorage.clear();
	}
};

```

356 357


358
#### 创建axios实例
359

360
**src/utils/request.ts**
361

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
```typescript
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {Session} from "@utils/storage";


// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API as any,
    timeout: 50000,
    headers: {'Content-Type': 'application/json;charset=utf-8'}
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        if (!config?.headers) {
            throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
        }
        if (Session.get('token')) {
            config.headers.Authorization = `${Session.get('token')}`;
        }

    }, (error) => {
        return Promise.reject(error);
    }
)

// 响应拦截器
service.interceptors.response.use(
    ({data}) => {
        // 对响应数据做点什么
        const {code, msg} = data;
        if (code === '00000') {
            return data;
        } else {
            ElMessage({
                message: msg || '系统出错',
                type: 'error'
            })
            return Promise.reject(new Error(msg || 'Error'))
        }
    },
    (error) => {
        const {code, msg} = error.response.data
        if (code === 'A0230') {  // token 过期
            Session.clear(); // 清除浏览器全部临时缓存
            window.location.href = '/'; // 跳转登录页
            ElMessageBox.alert('当前页面已失效,请重新登录', '提示', {})
                .then(() => {
                })
                .catch(() => {
                });
        }
        return Promise.reject(new Error(msg || 'Error'))
    }
);

// 导出 axios 实例
export default service
```
有来技术 已提交
423 424 425



有来技术 已提交
426 427 428 429 430 431 432 433 434 435
## HelloWorld.vue

```typescript
<template>
  <el-input v-model="num"/>
  <el-button @click="handleClick">点击+1</el-button>
</template>

<script  lang="ts">
import {defineComponent, computed} from 'vue'
436
import {useStore} from '@/store';
有来技术 已提交
437 438 439 440


export default defineComponent({
  setup() {
441
    const store = useStore()
有来技术 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    const num = computed(()=>{
      return store.state.count
    })
    const handleClick = () => {
      store.commit('increment')
    }
    return {
      num,
      handleClick
    }
  },
})
</script>
```

## App.vue

```typescript

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <router-view/>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

```

有来技术 已提交
479 480