Skip to content

Commit adfe56d

Browse files
author
dawpf
committed
文档更新
1 parent 2d4e255 commit adfe56d

File tree

3 files changed

+359
-18
lines changed

3 files changed

+359
-18
lines changed

README.md

Lines changed: 352 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,368 @@
1-
# demo
1+
# 项目说明
22

3-
## Project setup
4-
```
3+
```javascript
54
npm install
5+
npm run serve
66
```
77

8-
### Compiles and hot-reloads for development
8+
### 测试/生产 环境打包
9+
```javascript
10+
npm run dev
11+
npm run build
912
```
10-
npm run serve
13+
14+
## vue3.0环境变量配置
15+
16+
根据不同的指令:
17+
18+
```javascript
19+
npm run serve // 搭建本地环境
20+
npm run dev // 生成测试环境文件夹(可自定义为devdist)
21+
npm run build // 生成生产环境文件夹(一般默认为dist)
1122
```
1223

13-
### Compiles and minifies for production
24+
### 思路:
25+
26+
1,创建修改相关配置文件(Ctrl + C V即可)
27+
28+
2,封装 axios(根据配置文件,首先判断当前环境,获取对应环境的数据库地址作为当前环境下的基础地址,**拼接到** axios 里面的 url )
29+
30+
3,模块化开发
31+
32+
4,使用插件对代码进行测试判断环境配置是否成功
33+
34+
### 一 项目根目录新建配置文件
35+
36+
#### .env.development
37+
38+
```javascript
39+
module.export = {
40+
VUE_APP_URL = https://www.easy-mock.com/mock/example_dev
41+
}
42+
注:数据库地址不能加引号或分号!!
1443
```
15-
npm run build
44+
45+
#### .env.production
46+
47+
```javascript
48+
module.export = {
49+
VUE_APP_URL = https://www.easy-mock.com/mock/example_pro
50+
}
1651
```
1752

18-
### Run your tests
53+
#### package.json指令配置
54+
55+
```javascript
56+
"scripts": {
57+
"serve": "vue-cli-service serve", // 本地环境
58+
"build": "vue-cli-service build", // 生产环境
59+
"lint": "vue-cli-service lint",
60+
"dev": "vue-cli-service build --mode development" // 测试环境
61+
},
1962
```
20-
npm run test
63+
64+
#### vue.config.js
65+
66+
```javascript
67+
const path = require('path');
68+
69+
module.exports = {
70+
publicPath: '/', // 默认输出的路径 就是在当前地址栏后面添加的路径 若为 'ccc' 则为 http://localhost:8085/ccc/
71+
outputDir: process.env.NODE_ENV === "development" ? 'devdist' : 'dist', // 不同的环境打不同包名
72+
// css: { // 一次配置,全局使用,这个scss 因为每个文件都要引入
73+
// loaderOptions: {
74+
// sass: {
75+
// data: `@import "./src/assets/hotcss/px2rem.scss";`
76+
// }
77+
// }
78+
// },
79+
lintOnSave: false, // 关闭eslint
80+
productionSourceMap: true, // 生产环境下css 分离文件
81+
devServer: { // 配置服务器
82+
port: 8085, // 端口
83+
open: true,
84+
https: false,
85+
overlay: {
86+
warnings: true,
87+
errors: true
88+
}
89+
},
90+
configureWebpack: { // 覆盖webpack默认配置的都在这里
91+
resolve: { // 配置解析别名
92+
alias: {
93+
'@': path.resolve(__dirname, './src'),
94+
'@h': path.resolve(__dirname, './src/assets/hotcss'),
95+
'@s': path.resolve(__dirname, './src/assets/style'),
96+
'@i': path.resolve(__dirname, './src/assets/images'),
97+
}
98+
}
99+
}
100+
}
21101
```
22102

23-
### Lints and fixes files
103+
此时我们就可以获取到当前的环境( main.js )
104+
105+
```javascript
106+
console.log('当前环境数据地址:', process.env);
107+
// 打印如下:
108+
{
109+
VUE_APP_URL: "https://www.easy-mock.com/mock/example_dev", // 当前环境的数据库地址
110+
NODE_ENV: "development", // 当前环境
111+
BASE_URL: "/" // 默认输出路径 publicPath
112+
}
24113
```
25-
npm run lint
114+
115+
### 二 封装axios
116+
117+
在src / utils / http.js 文件夹下 对axios进行二次封装
118+
119+
```javascript
120+
import axios from 'axios'
121+
import { getToken } from '@/utils/auth'
122+
123+
// create an axios instance
124+
const request = axios.create({
125+
// baseURL: process.env.VUE_APP_URL,
126+
// 测试mock用地址
127+
baseURL: 'https://easy-mock.bookset.io/mock/5e90379d00bfc566e5bb1acb/example',
128+
129+
// 测试代理跨域用地址
130+
// baseURL: process.env.NODE_ENV === "development" ? '' : process.env.VUE_APP_URL,
131+
// withCredentials: true, // 跨域请求时发送cookie
132+
timeout: 60000
133+
})
134+
135+
const TOKEN = getToken() // 获取token
136+
137+
// 请求拦截器
138+
request.interceptors.request.use(
139+
config => {
140+
if (TOKEN) {
141+
// let each request carry token
142+
// ['X-Token'] is a custom headers key
143+
// please modify it according to the actual situation
144+
config.headers['Authorization'] = TOKEN
145+
}
146+
147+
// 扩展管理--expands:[]
148+
if (config.params && config.params.expandList) {
149+
const expandList = config.params.expandList
150+
const expands = {}
151+
if (expandList && expandList.length) {
152+
expandList.map((item, index) => {
153+
expands[`expands[${index}]`] = item
154+
})
155+
config.params = {
156+
...config.params,
157+
...expands
158+
}
159+
}
160+
delete config.params.expandList
161+
}
162+
163+
return config
164+
},
165+
error => {
166+
// do something with request error
167+
console.log(error)
168+
return Promise.reject(error)
169+
}
170+
)
171+
172+
// 响应拦截器
173+
request.interceptors.response.use(
174+
response => {
175+
// const res = response.data
176+
177+
// // if the custom code is not 20000, it is judged as an error.
178+
// if (res.code !== 20000) {
179+
// Message({
180+
// message: res.message || 'Error',
181+
// type: 'error',
182+
// duration: 5 * 1000
183+
// })
184+
185+
// // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
186+
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
187+
// // to re-login
188+
// MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
189+
// confirmButtonText: 'Re-Login',
190+
// cancelButtonText: 'Cancel',
191+
// type: 'warning'
192+
// }).then(() => {
193+
// store.dispatch('user/resetToken').then(() => {
194+
// location.reload()
195+
// })
196+
// })
197+
// }
198+
// return Promise.reject(new Error(res.message || 'Error'))
199+
// } else {
200+
// return res
201+
// }
202+
return response.data
203+
},
204+
error => {
205+
const data = error.response.data
206+
const status = error.response.status
207+
208+
// 对不同状态码进行管理
209+
if (status === 401) {
210+
console.log('登录已过期');
211+
} else if (status === 500) {
212+
console.log('服务器错误');
213+
}
214+
return Promise.reject(data.error)
215+
}
216+
)
217+
218+
export default request
219+
220+
26221
```
27222

28-
### Customize configuration
29-
See [Configuration Reference](https://cli.vuejs.org/config/).
223+
### 三 模块化开发
224+
225+
新建src / api / home.js(针对 home 模块的请求方法)
226+
227+
```javascript
228+
import $HTTP from "@/utils/HTTP.js"
229+
import Service from "@/utils/service.js" // 个人习惯把请求地址模块化统一管理
230+
231+
export function getMockData_home() {
232+
return $HTTP.get(Service.mock_home) // 等同于$HTTP.get('/home_url')
233+
}
234+
235+
export function postMockData_home(param) {
236+
return $HTTP.post(Service.mock_home,param)
237+
}
238+
239+
```
240+
241+
src / utils / service.js
242+
243+
```javascript
244+
export default {
245+
mock: '/my_url',
246+
mock_home: '/home_url'
247+
}
248+
```
249+
250+
在home组件里面就可以调用 getMockData_home 方法来获取数据了
251+
252+
```html
253+
<script>
254+
import { getMockData_home , postMockData_home } from '@/api/home.js'
255+
256+
export default {
257+
name: 'Home',
258+
async created() {
259+
let res_get = await getMockData_home()
260+
// console.log(res_get)
261+
let res_post = await postMockData_home({
262+
id:123,
263+
name:'zhangsan',
264+
...
265+
})
266+
// console.log(res.post)
267+
}
268+
}
269+
</script>
270+
```
271+
272+
### 四 代码测试
273+
274+
```javascript
275+
npm i serve -g // 全局安装 serve
276+
npm run dev // 生成测试环境代码(根据vue.config.js配置,项目根目录会出现一个devdist文件夹)
277+
serve devdist // 模拟线上服务器,在本地新建服务器并运行代码
278+
```
279+
280+
![测试](/Users/macadmin/Desktop/vue3.0环境变量配置/测试.png)
281+
282+
测试环境配置已完成,devdist 文件夹上传至测试环境服务器即可
283+
284+
生产环境同理(生产环境文件夹默认为 dist )
285+
286+
## 服务器代理解决跨域问题
287+
288+
### 思路:
289+
290+
我们想要访问的目标接口地址是 http://t.yushu.im/v2/movie/in_theaters
291+
现在,我们把这串地址的 http://t.yushu.im 这部分用拦截器 /api 替代,也就是说,当服务器启动的时候,在文件中读取到 ‘ /api ’ 这串字符串的时候,会变成 http:localhost/8080/api/v2/movie/in_theaters,而此时路径重写设置为忽略拦截器的名字,也就是说不包含拦截器的名字,因此,访问路径会变成这样,是这样 http:localhost/8080/v2/movie/in_theaters,最后,路径就成功伪装,顺利闯过了浏览器的关卡,就可以正常获取到数据
292+
293+
### Vue.config.js
294+
295+
```javascript
296+
const path = require('path');
297+
298+
module.exports = {
299+
publicPath: '/', // 默认输出的路径 就是在当前地址栏后面添加的路径 若为 'ccc' 则为 http://localhost:8085/ccc/
300+
outputDir: process.env.NODE_ENV === "development" ? 'devdist' : 'dist', // 不同的环境打不同包名
301+
lintOnSave: false, // 关闭eslint
302+
productionSourceMap: true, // 生产环境下css 分离文件
303+
devServer: { // 配置服务器
304+
port: 8085, // 端口
305+
open: true,
306+
https: false,
307+
overlay: {
308+
warnings: true,
309+
errors: true
310+
},
311+
proxy: { // 使用本地服务器代理解决跨域问题
312+
'/api': {
313+
//代理的目标地址,demo 要访问的数据为:http://t.yushu.im/v2/movie/in_theaters
314+
target: 'http://t.yushu.im',
315+
changeOrigin: true, //是否设置同源,输入是的
316+
pathRewrite: { //路径重写
317+
'/api': '' //选择忽略拦截器里面的单词
318+
}
319+
}
320+
}
321+
},
322+
configureWebpack: { // 覆盖webpack默认配置的都在这里
323+
resolve: { // 配置解析别名
324+
alias: {
325+
'@': path.resolve(__dirname, './src'),
326+
'@h': path.resolve(__dirname, './src/assets/hotcss'),
327+
'@s': path.resolve(__dirname, './src/assets/style'),
328+
'@i': path.resolve(__dirname, './src/assets/images'),
329+
}
330+
}
331+
}
332+
}
333+
```
334+
335+
home.js 中使用
336+
337+
```javascript
338+
import $HTTP from "@/utils/HTTP.js"
339+
import Service from "@/utils/service.js" // 个人习惯把请求地址模块化统一管理
340+
341+
export function getMockData_home() {
342+
return $HTTP.get(Service.mock) // 等同于$HTTP.get('/home_url')
343+
}
344+
345+
export function getProxyData() {
346+
return $HTTP.get('/api/v2/movie/in_theaters')
347+
}
348+
```
349+
350+
此时,就可以通过调用 getProxyData 获取到 http://t.yushu.im/v2/movie/in_theaters 地址里面的数据
351+
352+
### 注意
353+
354+
HTTP.js 中,开发环境下的数据库地址需要改为 ' '
355+
356+
```javascript
357+
const request = axios.create({
358+
// baseURL: process.env.VUE_APP_URL,
359+
baseURL: process.env.NODE_ENV === "development" ? '' : process.env.VUE_APP_URL,
360+
withCredentials: true, // 跨域请求时发送cookie
361+
timeout: 60000
362+
})
363+
```
364+
365+
**总结:当后端数据库已经配置好,前端不需要进行代理配置,按照 开发环境 / 生产环境 配置响应的 baseUrl 即可,如果后端不支持跨域,则前端在本地环境进行数据获取的时候需要进行代理配置**
366+
367+
368+

src/utils/HTTP.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import { getToken } from '@/utils/auth'
44
// create an axios instance
55
const request = axios.create({
66
// baseURL: process.env.VUE_APP_URL,
7-
// baseURL: 'https://easy-mock.bookset.io/mock/5e90379d00bfc566e5bb1acb/example', // 测试用地址
8-
baseURL: process.env.NODE_ENV === "development" ? '' : process.env.VUE_APP_URL, // 使用代理时,baseURL 在本地服务器设置为空
7+
baseURL: 'https://easy-mock.bookset.io/mock/5e90379d00bfc566e5bb1acb/example', // 测试mock用地址
8+
// baseURL: process.env.NODE_ENV === "development" ? '' : process.env.VUE_APP_URL, // 测试代理跨域用地址
99
// withCredentials: true, // 跨域请求时发送cookie
1010
timeout: 60000
1111
})

0 commit comments

Comments
 (0)