1. 前言
後臺管理系統面對的羣體還是很廣的。
項目使用Vue
+Element
搭建;在當前搭建中會使用vue-cli
腳手架快速創建一個Vue
項目,並且能請求接口獲取到數據。
現在就來創建它,運行它。
2. 源碼
完整項目地址:https://github.com/intomylife/osc-front
v1.0 標籤地址:https://github.com/intomylife/osc-front/releases/tag/v1.0
注:對於標籤的說明「初學者商城」- 寫在最前面 #5.1
3. 環境
- node 12.11.1
- npm 6.11.3
- vue 2.9.6
4. 工具
- Visual Studio Code
5. 搭建
5.1 創建項目
- 打開終端
- 輸入命令
vue
如果不存在則輸入命令sudo npm install -g vue-cli
全局安裝 vue-cli - 進入到項目預存放目錄
- 輸入命令
vue init webpack projectName
在當前目錄創建一個基於 webpack 的項目 - 接下來就是填寫一些關於項目的信息就創建完畢
MacBook-Pro:Downloads zouwencong$ vue init webpack osc-front
? Project name osc-front
? Project description A Vue.js project
? Author 鄒文聰 <[email protected]>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recom
mended) npm
vue-cli · Generated "osc-front".
# Installing project dependencies ...
# ========================
...省略部分...
# ========================
To get started:
cd osc-front
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
- Project name(項目名稱):直接回車,使用默認,後面也可以更改
- Project description(項目描述):直接回車,使用默認,後面也可以更改
- Author(作者信息):直接回車,使用默認,後面也可以更改
- Vue build(是否安裝編譯器):直接回車
- Install vue-router?(是否安裝
vue
路由):回車表示yes
,這裏選擇安裝,直接回車 - Use ESLint to lint your code?(是否校驗代碼規範): 輸入
n
,回車;在後續博客中會專門來安裝這個插件 - Set up unit tests(是否安裝單元測試工具):輸入
n
,回車 - Setup e2e tests with Nightwatch?(是否安裝模擬測試工具):輸入
n
,回車 - Should we run
npm install
for you after the project has been created? (recom
mended)(使用哪種方式安裝依賴包):直接回車,使用npm
來安裝依賴 - 創建成功後,就可以運行了
MacBook-Pro:Downloads zouwencong$ cd osc-front
MacBook-Pro:osc-front zouwencong$ npm run dev
> [email protected] dev /Users/zouwencong/Downloads/osc-front
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
13% building modules 25/31 modules 6 active ...ncong/Downloads/osc-front/src/App.vue{ parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }.
95% emitting
DONE Compiled successfully in 1681ms 17:45:38
I Your application is running here: http://localhost:8080
- 訪問
http://localhost:8080/
即可看到Vue主頁面 ctrl
+c
先停止運行- 使用
vsCode
打開代碼目錄
5.2 更改端口
注:習慣性會把前端頁面端口更改爲9527
- 找到
config - index.js
文件並打開 - 搜索
port: 8080
- 把
8080
更改爲9527
5.3 跨域
注:這裏主要解決的是開發時請求跨域問題
- 找到
config - index.js
文件並打開 - 搜索
proxyTable: {}
- 配置如下
proxyTable: {
'/api' : {
// target: 'https://xxx.com',
target: 'http://127.0.0.1:8000',
changeOrigin: true,
pathRewrite: {
'^/api': '' // api 開頭的接口都使用此代理,如果添加了此行代碼,那麼意思就是在接口中去掉 api
},
}
},
- 這裏配置後,項目中以
/api
開頭的請求都會被攔截下來,轉發到地址http://127.0.0.1:8000
,並截取/api
部分 - 例如地址
http://127.0.0.1:9527/api/baseService
請求會轉發到地址http://127.0.0.1:8000/baseService
- 爲什麼是轉發到
8000
端口?因爲8000
是接口中的網關端口
5.4 環境變量
注:項目中專門有一個地方用來存放環境變量,並且不同的環境變量(開發、測試,生產等)由單獨的文件來存放
開發環境:
- 找到
config - dev.env.js
文件並打開 - 添加
VUE_APP_BASE_API
和VUE_APP_BASE_URL
,如下
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
VUE_APP_BASE_API: '"/api"',
VUE_APP_BASE_URL: '"/baseService"'
})
VUE_APP_BASE_API
用來拼接到請求的開頭部分,值/api
也剛好是對應上面跨域中會被攔截的請求的開頭VUE_APP_BASE_URL
用來拼接到請求的中間部分,值baseService
也剛好是對應接口中網關路由攔截的請求的開頭
生產環境:
- 找到
config - prod.env.js
文件並打開 - 同樣添加
VUE_APP_BASE_API
和VUE_APP_BASE_URL
,如下
'use strict'
module.exports = {
NODE_ENV: '"production"',
VUE_APP_BASE_API: '"/api"',
VUE_APP_BASE_URL: '"/baseService"'
}
- 然而這裏生產時的用法與開發時不同,生產時跨域使用
Nginx
解決的,具體再後面部署時再展開,畢竟當前搭建只是在本地運行
5.5 封裝請求
注:這裏使用的是axios
方式請求的數據
import axios from 'axios'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
// baseURL: "http://xxx", // api 的 base_url
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// debugger
// Do something before request is sent
return config
},
error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
}
)
// respone interceptor
service.interceptors.response.use(
/**
* 下面的註釋爲通過在response裏,自定義code來標示請求狀態
* 當code返回如下情況則說明權限有問題,登出並返回到登錄頁
* 如想通過xmlhttprequest來狀態碼標識 邏輯可寫在下面error中
* 以下代碼均爲樣例,請結合自生需求加以修改,若不需要,則可刪除
*/
response => {
console.log(response.data)
return response
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default service
- 專門建一個目錄,用來存放工具類,如當前文件存放至
src - utils - request.js
- 這個封裝的請求工具類一共分爲五大部分
① 引入axios
② 創建axios
實例,並配置baseURL
爲process.env.VUE_APP_BASE_API
,也就是上面剛剛配置的環境變量
③ 配置請求攔截器(可以用來設置統一的請求頭,如讓每個請求攜帶用戶憑證token
)
④ 配置響應攔截器(可以用來處理統一的響應結果,如不同的狀態碼做不同的處理)
⑤ 導出(對外輸出本模塊供調用)
5.6 封裝接口
注:一般每個功能模塊的接口都會寫在一個單獨的文件中,方便查閱方便管理
import request from '@/utils/request'
// 獲取訪問次數
export function getComeCounts() {
return request({
url: `${process.env.VUE_APP_BASE_URL}/visit/toVisit`,
method: 'get'
})
}
- 文件位置在:src - api - base.js
- 引入上面封裝好的請求工具類
- process.env.VUE_APP_BASE_URL:獲取環境變量
- url:請求地址,完整地址爲
http://127.0.0.1:9527/baseURL/${process.env.VUE_APP_BASE_URL}/visit/toVisit
->http://127.0.0.1:9527/api/baseService/visit/toVisit
- method:請求方式
5.7 調用接口
注:直接寫在了默認的HelloWorld.vue
文件中(刪除了原有部分代碼)
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
// 引入接口
import { getComeCounts } from "@/api/base";
export default {
name: "HelloWorld",
data() {
return {
msg: ""
};
},
created() {
// 調用獲取訪問次數方法
this.comeCounts();
},
mounted() {},
methods: {
// 獲取訪問次數
comeCounts() {
// 調用獲取訪問次數接口
getComeCounts().then(res => {
// 打印結果
console.log("HelloWorld: " + res);
// 設值
this.msg = res.data;
});
}
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
- 頁面加載時會調用
this.comeCounts()
方法 comeCounts()
方法調用了上面封裝的接口- 把接口返回的數據賦值到了
data()
中,並顯示到頁面上
6. 啓動
6.1 接口
- 如何啓動接口請前往:「初學者商城」- 搭建基礎架構(接口)
6.2 後臺管理系統
- 在
vsCode
中打開終端(快捷鍵:ctrl
+~
) - 輸入
npm install --save axios
,安裝axios
- 輸入
npm run dev
,回車
7. 驗證
- 訪問
http://localhost:9527
- 顯示
success
,表示成功
8. 結語
這也算是真正意義上的前後端分離了。阿,快樂。
9. 相關文章
9.1 準備工作
9.2 搭建基礎架構
9.3 搭建本地開發環境
希望能夠幫助到你
over