前言
本文的案例是基於Vue-admin-template項目改造的簡化版Vue后台管理模板案例
主要是想幫助那些和我一樣從后端入門並且想要快速上手Vue后台管理系統的開發
本文在SpringBoot、Element UI、Vue框架之上實現的小案例,並非從零開始
各位如果遇到難題,可以向百度和谷歌虛心求教,我也是一路折騰過來才寫下此文
技術棧
- SpringBoot2.3
- Vue-admin-template4.3
- axios
- mysql5.7
- mybatis
案例演示
案例實踐
1.下載項目,按照操作把項目跑起來
# 去github克隆項目(我的版本是4.0版本vue-admin-template)
git clone https://github.com/PanJiaChen/vue-admin-template
# 進入目錄
cd vue-admin-template
# 安裝依賴(前提需要自行安裝配置好node.js)
npm install --registry=https://registry.npm.taobao.org
# 運行
npm run dev
2.在側邊欄新增導航路由頁面
-
新建文件。在src/views/ 新建一個文件夾 student,在此目錄下新建文件 index.vue
-
添加路由。打開 src/router/index.js,此文件為該項目的后台路由配置文件。在constantRoutes這個數組中,添加路由的格式如下:
{ path: '/student', // 頁面訪問的url一級路徑 component: Layout,// 這是全局統一的一個布局文件,暫時不需要修改 children: [ { path: 'index',// 頁面訪問的url二級路徑 name: 'Student', component: () => import('@/views/student/index'), // 導入剛才新建vue文件的路徑 meta: { title: '學生', icon: 'form' } // title 是側邊欄的名字,icon是圖標 } ] },
這一步我們完成路由配置,之后框架會自動地根據路由配置文件,生成邊側導航條目,剩下的工作就是寫好那個index.vue組件的內容,這里包含兩部分內容:簡單編寫組件和發送網絡請求
3.簡單編寫組件,后面再美化組件
編程就是由簡單慢慢到復雜,我們先在頁面上完成一個簡單的頁面,只制作頁面上輸出123的頁面組件
<template>
<!-- div是作為根元素,必須要有這個元素 -->
<div>
123
</div>
</template>
<script>
export default {
data() {
return {
// 這里定義數據格式
}
},
mounted() {
// 這里是vue鈎子函數,不理解的話就是js的入口
},
methods: {
// 這是定義方法的區域
}
}
</script>
<style scoped>
// 這是寫CSS內容的區域
</style>
如果上述步驟都沒錯的話,你可以得到下面的頁面效果
4.網絡請求基礎配置
4.1 跨域訪問資源
本文中開發的頁面是運行部署在前端服務器上,端口是http://localhost:9528,后台的數據是在后端服務器上,端口是http://localhost:8080, 兩者之間端口不一致,需要跨域名訪問資源,用到的是代理模式,這里就涉及到跨域訪問資源和同源策略這兩個概念,本文不做深入講解,暫且只需要知道
在項目上線后,對於CORS跨域資源訪問的問題,可以用類似的方案(Nginx反向代理)在前端解決。
4.2 代理模式
生活中的代理模式例子:小明要買一台高性能的華碩電腦,去街上的實體店看到只有樣板的華碩電腦,於是付錢給經銷商,經銷商拿着錢去找華碩廠家拿到高性能的華碩電腦,然后回到實體店把電腦交付給小明,同時還賺取了中間差價,這就是一個典型的代理模式案例
4.3 開發中的代理模式
vue-admin-template是基於vue-cli開發出來的,部署在前端的服務器,
-
瀏覽器訪問這些頁面組件就相當於小明看到華碩電腦樣板,
-
前端服務器代理轉發請求到后端服務器相當於經銷商把錢付給廠家,
-
后端服務器返回數據給前端服務器前端服務器,服務器再返回數據給瀏覽器
就相當於廠家交付電腦給經銷商,經銷商拿到后再交付電腦給小明
登錄接口的實現我在上一篇文章中已經很詳細地講解過,所以這篇文章中不會有過多的關於登錄接口的實現的細節
只是在上篇的基礎上進行對接口代理進行的改動,不懂的可以先去看看SpringBoot實現Vue-admin-template登錄
配置代理
因為存在跨域資源請求的問題,前后端交互的網絡請求在底層由node.js代理,有興趣的可以看下官方文檔
打開根目錄下的vue.config.js文件,在devServer中添加proxy區域的代碼
devServer: {
port: port,
open: false,
overlay: {
warnings: false,
errors: true
},
// 代理所有以‘/admin’開頭的網絡請求
proxy: {
'/admin': {
target: `http://localhost:8080/`, //后台服務地址(Springboot內置tomcat默認的地址)
changeOrigin: true,
pathRewrite: {
// 路徑重寫,可以理解為路徑重新賦值
// '^/admin': '/'
// pathRewrite: {'^/admin': '/'} 重寫之后url為 http://localhost:8080/xxxx
// pathRewrite: {'^/admin': '/admin'}
// 重寫之后url為http://localhost:8080/admin/xxxx
}
}
}
}
配置地址
生產環境與開發環境通常有不同的服務地址。編輯 .env.development 以及 .env.production 這兩個文件,修改其中的 VUE_APP_BASE_API 配置項即可
本文只涉及開發,就以開發環境為例:
VUE_APP_BASE_API = '/admin'
配置攔截器
打開src/utils/request.js,它封裝了一個axios請求對象,它就是jquery中的ajax那樣理解着用,應該很快就能上手,在這個項目的數據交互的請求都是基於axios來處理的。
我們可以在發送請求之前規定一些后端數據返回的格式,方便我們自己調試和定位網絡請求是否正確響應和輸出。比如根據服務端的狀態碼判斷請求是否正常,若不正常給出相應的提示。
service.interceptors.response.use(
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
// 個性化定制響應的狀態碼不為20000,它會認為這是一個錯誤的響應
if (res.code !== 20000) { // 這里可以根據業務修改為res.code !== 200 我演示就懶得改
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
// 50008: 非法的token 50012: 其他客戶端登錄了; 50014: Token 過期了;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
// 重新設置token
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
// 返回一個Promise對象,ES6中的方便處理異步請求的對象,可以查閱MDN文檔理解
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
)
配置全局請求
在src/main.js加入下面的代碼配置,這樣我們就可以在組件的腳本使用全局發起請求
Vue.prototype.http = request
1.全局發起請求
this.http({
// 此處寫不同業務對應的url,框架會自動與baseURL拼接
url: "getInfo?id=6",
data: {},
method: "GET"
}).then(
res => {
// 請求成功后的處理
console.log("res :", res);
},
err => {
// 請求失敗后的處理
console.log("err :", err);
}
);
2.單一封裝好請求
按照比較好的前端開發模式,應該是把網絡請求統一抽離到單一文件,然后在每個具體的頁面進行對服務端數據的處理。 比如下面的這種形式,首先創建文件src/api/student.js,把在student組件中需要用到的網絡請求都寫入此文件。
// src/api/student.js
import request from '@/utils/request'
export function getStudentList(params) {
return request({
url: 'getTableData',
method: 'get',
params
})
}
3.登錄接口的實現適配
在src\api\user.js中修改了login的接口代碼
export function login(data) {
return request({
url: '/user/login',
method: 'post',
data
})
}
4.前后登錄接口數據流細節對比
新的登錄接口
上篇文章舊的登錄接口前端做了小改動和SpringBoot中的LoginController做了小改動
5.后端SpringBoot搭建接口返回數據
5.1 pom.xml引入依賴
<!--web開發依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--mysql依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--lombok依賴-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
5.2 SpringBoot配置數據庫和端口
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
server:
port: 8080 // 端口號
servlet:
context-path: /admin // 項目根路徑
5.3 實體類
@Data//使用這個注解就默認幫我們生成getter和setter以及toString等
@NoArgsConstructor //lombok生成無參數構造函數
public class Student {
private Integer id;
private String name;
private Integer age;
private String className;
private String gender;
private String marjor;
private String department;
}
5.4 mapper接口
@Mapper
public interface StudentMapper {
@Select("select * from student where id=#{id}")
Student findStudentById(Integer id);
@Insert("insert into student(name,age)values(#{name},#{age})")
void insertStudent(Student student);
@Update("update student set name=#{name} where id=#{id}")
void updateStudent(Student student);
@Delete("delete from student where id=#{id}")
void deleteStudentById(Integer id);
@Select("select * from student")
List<Student> findAll();
}
5.5 controller類
這里省略了dao層和service層,主要是寫demo貪方便,實際開發中還是要遵循3層結構開發
@RestController
public class StudentController {
@Autowired
private StudentMapper studentMapper;
@CrossOrigin // 跨域訪問
@GetMapping(value = "/getTableData")
public Map finAllStudent(){
List<Student> studentList = studentMapper.findAll();
HashMap<String, Object> responseData = new HashMap<>();
responseData.put("code",20000);
responseData.put("data",studentList);
return responseData;
}
}
6.使用Element UI美化組件
現在我們可以在student.vue中用Element UI所提供的組件來美化我們student頁面組件
-
Table組件寫一個表格數據展示區域,
-
用Element UI的柵格布局和Form組件在表格上方編寫一個搜索區域,用來做日常的增刪改查功能
-
用Element UI的 Pagination 組件在表格上方編寫一個搜索區域,用來做日常的增刪改查功能
進入Element UI Table表格 ,Pagination分頁,Layout 布局, Form 表單組件的說明文檔,復制粘貼對應的代碼。
vue-admin-template對於Element UI已經進行了全局引入,所以這些組件拿來即用。
這里暫且以獲取后端的返回的數據作為案例,只要能寫通這個區域,其他的基本上能一通百通,也就自然會增刪改
<template>
<!-- 數據表格區域 -->
<div class="data-content">
<el-table
:data="tableData"
style="width: 100%"
border
>
<el-table-column
type="selection"
width="55"
/>
<el-table-column
type="index"
label="序號"
width="80px"
/>
<el-table-column
prop="name"
label="姓名"
width="180"
/>
<el-table-column
prop="age"
label="年齡"
/>
<el-table-column
prop="gender"
label="性別"
/>
<el-table-column
prop="className"
label="班級"
/>
<el-table-column
prop="marjor"
label="專業"
/>
<el-table-column
prop="department"
label="系別"
/>
</el-table>
</div>
</template>
在組件裝載時請求數據
<script>
import { getStudentList } from '@/api/student.js' // 導入封裝過的網絡請求專門用於student相關api
export default {
data() {
return {
// 表格數據
tableData: []
}
},
mounted() { // mounted鈎子函數(生命周期函數)相當window.onload函數,隨頁面一加載執行
// 單一網絡請求在student.js經過封裝統一處理,這里需要導入這個文件
getStudentList({}).then(res => {
console.log('tableData :', res)
this.tableData = res.data
}, err => {
console.log('err :', err)
})
},
methods: {
// 暫時沒用到定義方法,可以不寫
}
}
</script>
數據正常的頁面實際效果
數據正常的頁面動態效果
后序
文章雖然不多圖,但大體的流程都詳細講解了,礙於文章篇幅太長,
如果把增刪改查放在一篇文章里面記錄,就會很容易產生閱讀疲勞
所以暫時只把查詢作為案例講解,后面會把剩下的增刪改補上
文章配套源碼已傳至百度網盤,拿來即用(github好像也有,可以自行查看以往的文章)
鏈接: https://pan.baidu.com/s/1u9DY3zzRn4-r9Ih_OAZeJg 提取碼: c4k3