樂優商城(三)商品分類管理
目錄
後臺功能——商品分類管理
商城中最重要的就是商品,當商品數目增多後,需要對商品進行分類,而且不同的商品會有不同的品牌資訊。具體關係如下圖所示:
-
一個商品分類下有很多商品
-
一個商品分類下有很多品牌
-
而一個品牌,可能屬於不同的分類
-
一個品牌下也會有很多商品
一、資料
匯入後:
二、頁面實現
效果圖:
2.1 頁面分析
採用樹結構展示,頁面對應的是/pages/item/Category.vue
<template> <v-card> <v-flex xs12 sm10> <v-tree ref="tree" url="/item/category/list" :isEdit="isEdit" @handleAdd="handleAdd" @handleEdit="handleEdit" @handleDelete="handleDelete" @handleClick="handleClick" /> </v-flex> </v-card> </template>
這裡面最主要的就是自定義元件v-tree,具體的使用方法如下:
屬性列表
屬性名稱 | 說明 | 資料型別 | 預設值 |
---|---|---|---|
url | 用來載入資料的地址,即延遲載入 | String | - |
isEdit | 是否開啟樹的編輯功能 | boolean | false |
treeData | 整顆樹資料,這樣就不用遠端載入了 | Array | - |
這裡推薦使用url進行延遲載入,每當點選父節點時,就會發起請求,根據父節點id查詢子節點資訊。當有treeData屬性時,就不會觸發url載入。
遠端請求返回的結果格式:
事件列表
事件名稱 | 說明 | 回撥引數 |
---|---|---|
handleAdd | 新增節點時觸發,isEdit為true時有效 | 新增節點node物件,包含屬性:name、parentId和sort |
handleEdit | 當某個節點被編輯後觸發,isEdit為true時有效 | 被編輯節點的id和name |
handleDelete | 當刪除節點時觸發,isEdit為true時有效 | 被刪除節點的id |
handleClick | 點選某節點時觸發 | 被點選節點的node物件,包含全部資訊 |
一個node的完整資訊
- 父節點
- 子節點
2.2 功能實現
2.2.1 url非同步請求
- 先按下圖進行修改
- 然後重新整理頁面,開啟除錯可以看到傳送的請求地址如下圖所示
- 最後需要做的就是編寫後臺介面
2.2.2 後臺介面實現
實體類
在leyou-item-interface中新增category實體類:
@Table(name="tb_category")
/**
* @author li
* @time 2018/8/7
* @feature: 商品分類對應的實體
*/
public class Category implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String name;
private Long parentId;
private Boolean isParent;
/**
* 排序指數,越小越靠前
*/
private Integer sort;
//get和set方法省略
//注意isParent的set和get方法
}
需要注意的是,這裡要用到jpa的註解,因此我們在ly-item-iterface
中新增jpa依賴
<dependencies>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
Controller
編寫一個controller一般需要知道四個內容:
-
請求方式:決定我們用GetMapping還是PostMapping
-
請求路徑:決定對映路徑
-
請求引數:決定方法的引數
-
返回值結果:決定方法的返回值
在剛才頁面發起的請求中,我們就能得到絕大多數資訊:
-
請求方式:Get
-
請求路徑:/api/item/category/list。其中/api是閘道器字首,/item是閘道器的路由對映,真實的路徑應該是/category/list
-
請求引數:pid=0,根據tree元件的說明,應該是父節點的id,第一次查詢為0,那就是查詢一級類目
-
返回結果:json陣列
/**
* @Author: 98050
* Time: 2018-08-07 19:18
* Feature:
*/
@RestController
@RequestMapping("category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 根據父節點查詢商品類目
* @param pid
* @return
*/
@GetMapping("/list")
public ResponseEntity<List<Category>> queryCategoryByPid(@RequestParam("pid") Long pid){
List<Category> list=this.categoryService.queryCategoryByPid(pid);
if (list == null){
//沒有找到返回404
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
//找到返回200
return ResponseEntity.ok(list);
}
}
Servicer
定義對應的介面和實現類
/**
* @Author: 98050
* Time: 2018-08-07 19:16
* Feature: 分類的業務層
*/
public interface CategoryService {
/**
* 根據id查詢分類
* @param pid
* @return
*/
List<Category> queryCategoryByPid(Long pid);
}
/**
* @Author: 98050
* Time: 2018-08-07 19:16
* Feature: 分類的業務層
*/
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
private CategoryMapper categoryMapper;
/**
* 根據父節點id查詢分類
* @param pid
* @return
*/
@Override
public List<Category> queryCategoryByPid(Long pid) {
Category t=new Category();
t.setParentId(pid);
return this.categoryMapper.select(t);
}
}
Mapper
使用通用mapper來簡化開發:
注意:一定要加上註解@org.apache.ibatis.annotations.Mapper
/**
* @Author: 98050
* @Time: 2018-08-07 19:15
* @Feature:
*/
@org.apache.ibatis.annotations.Mapper
public interface CategoryMapper extends Mapper<Category> {
}
測試
不經過閘道器,直接訪問:
通過閘道器訪問:
後臺頁面訪問:
報錯,跨域問題~
2.3 解決跨域請求
2.3.1 什麼是跨域
跨域是指跨域名的訪問,以下情況都屬於跨域:
跨域原因說明 | 示例 |
---|---|
域名不同 | www.jd.com 與 www.taobao.com |
域名相同,埠不同 | www.jd.com:8080 與 www.jd.com:8081 |
二級域名不同 | item.jd.com 與 miaosha.jd.com |
如果域名和埠都相同,但是請求路徑不同,不屬於跨域,如:
www.jd.com/item
www.jd.com/goods
但剛才是從manage.leyou.com
去訪問api.leyou.com
,這屬於二級域名不同,所以會產生跨域。
跨域不一定會有跨域問題。因為跨域問題是瀏覽器對於ajax請求的一種安全限制:一個頁面發起的ajax請求,只能是於當前頁同域名的路徑,這能有效的阻止跨站攻擊。因此:跨域問題 是針對ajax的一種限制。
2.3.2 解決跨域問題的方案
目前比較常用的跨域解決方案有3種:
-
Jsonp
最早的解決方案,利用script標籤可以跨域的原理實現。
限制:
-
需要服務的支援
-
只能發起GET請求
-
-
nginx反向代理
思路是:利用nginx反向代理把跨域為不跨域,支援各種請求方式
缺點:需要在nginx進行額外配置,語義不清晰
-
CORS
規範化的跨域請求解決方案,安全可靠。
優勢:
-
在服務端進行控制是否允許跨域,可自定義規則
-
支援各種請求方式
缺點:
-
會產生額外的請求
-
2.3.3 cors解決跨域問題
- 什麼是cors?
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。它允許瀏覽器向跨源伺服器,發出
XMLHttpRequest
請求,從而克服了AJAX只能同源使用的限制。CORS需要瀏覽器和伺服器同時支援。目前,所有瀏覽器都支援該功能,IE瀏覽器不能低於IE10。
瀏覽器端:
目前,所有瀏覽器都支援該功能(IE10以下不行)。整個CORS通訊過程,都是瀏覽器自動完成,不需要使用者參與。
服務端:
CORS通訊與AJAX沒有任何差別,因此你不需要改變以前的業務邏輯。只不過,瀏覽器會在請求中攜帶一些頭資訊,我們需要以此判斷是否執行其跨域,然後在響應頭中加入一些資訊即可。這一般通過過濾器完成即可。
- 原理剖析
瀏覽器會將ajax請求分為兩類,其處理方案略有差異:簡單請求、特殊請求。
簡單請求
只要同時滿足以下兩大條件,就屬於簡單請求。:
(1) 請求方法是以下三種方法之一:
HEAD
GET
POST
(2)HTTP的頭資訊不超出以下幾種欄位:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限於三個值
application/x-www-form-urlencoded
、multipart/form-data
、text/plain
當瀏覽器發現的ajax請求是簡單請求時,會在請求頭中攜帶一個欄位:
Origin
.Origin中會指出當前請求屬於哪個域(協議+域名+埠)。服務會根據這個值決定是否允許其跨域。
如果伺服器允許跨域,需要在返回的響應頭中攜帶下面資訊:
Access-Control-Allow-Origin: http://manage.leyou.com Access-Control-Allow-Credentials: true Content-Type: text/html; charset=utf-8
Access-Control-Allow-Origin:可接受的域,是一個具體域名或者*,代表任意
Access-Control-Allow-Credentials:是否允許攜帶cookie,預設情況下,cors不會攜帶cookie,除非這個值是true
注意:
如果跨域請求要想操作cookie,需要滿足3個條件:
服務的響應頭中需要攜帶Access-Control-Allow-Credentials並且為true。
瀏覽器發起ajax需要指定withCredentials 為true
響應頭中的Access-Control-Allow-Origin一定不能為*,必須是指定的域名
特殊請求
不符合簡單請求的條件,會被瀏覽器判定為特殊請求,,例如請求方式為PUT。
預檢請求
特殊請求會在正式通訊之前,增加一次HTTP查詢請求,稱為"預檢"請求(preflight)。
瀏覽器先詢問伺服器,當前網頁所在的域名是否在伺服器的許可名單之中,以及可以使用哪些HTTP動詞和頭資訊欄位。只有得到肯定答覆,瀏覽器才會發出正式的
XMLHttpRequest
請求,否則就報錯。一個“預檢”請求的樣板:
OPTIONS /cors HTTP/1.1 Origin: http://manage.leyou.com Access-Control-Request-Method: PUT Access-Control-Request-Headers: X-Custom-Header Host: api.leyou.com Accept-Language: en-US Connection: keep-alive User-Agent: Mozilla/5.0...
與簡單請求相比,除了Origin以外,多了兩個頭:
Access-Control-Request-Method:接下來會用到的請求方式,比如PUT
Access-Control-Request-Headers:會額外用到的頭資訊
預檢請求的響應
服務的收到預檢請求,如果許可跨域,會發出響應:
HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://manage.leyou.com Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: X-Custom-Header Access-Control-Max-Age: 1728000 Content-Type: text/html; charset=utf-8 Content-Encoding: gzip Content-Length: 0 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain
除了
Access-Control-Allow-Origin
和Access-Control-Allow-Credentials
以外,這裡又額外多出3個頭:
Access-Control-Allow-Methods:允許訪問的方式
Access-Control-Allow-Headers:允許攜帶的頭
Access-Control-Max-Age:本次許可的有效時長,單位是秒,過期之前的ajax請求就無需再次進行預檢了
如果瀏覽器得到上述響應,則認定為可以跨域,後續就跟簡單請求的處理是一樣的了。
- 實現
雖然原理比較複雜,但是:
-
瀏覽器端都有瀏覽器自動完成,我們無需操心
-
服務端可以通過攔截器統一實現,不必每次都去進行跨域判定的編寫。
事實上,SpringMVC已經幫我們寫好了CORS的跨域過濾器:CorsFilter ,內部已經實現了剛才所講的判定邏輯,我們直接用就好了。
在ly-api-gateway
中編寫一個配置類,並且註冊CorsFilter:
package com.leyou.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author li
* @time:2018/8/7
* 處理跨域請求的過濾器
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.新增CORS配置資訊
CorsConfiguration config = new CorsConfiguration();
//1) 允許的域,不要寫*,否則cookie就無法使用了
config.addAllowedOrigin("http://manage.leyou.com");
//2) 是否傳送Cookie資訊
config.setAllowCredentials(true);
//3) 允許的請求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允許的頭資訊
config.addAllowedHeader("*");
//2.新增對映路徑,我們攔截一切請求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
2.3.4 重新測試
頁面:
2.4 功能完善
目前只完成了顯示功能,需要新增增、刪、改功能
2.4.1 非同步查詢工具axios
非同步查詢資料,自然是通過ajax查詢,但jQuery與MVVM的思想不吻合,而且ajax只是jQuery的一小部分。因此不可能為了發起ajax請求而去引用這麼大的一個庫,所以使用Vue官方推薦的ajax請求框架:axios。
入門
axios的GET請求語法:
axios.get("/item/category/list?pid=0") // 請求路徑和請求引數拼接
.then(function(resp){
// 成功回撥函式
})
.catch(function(){
// 失敗回撥函式
})
// 引數較多時,可以通過params來傳遞引數
axios.get("/item/category/list", {
params:{
pid:0
}
})
.then(function(resp){})// 成功時的回撥
.catch(function(error){})// 失敗時的回撥
axios的POST請求語法: (新增一個使用者)
axios.post("/user",{
name:"Jack",
age:21
})
.then(function(resp){})
.catch(function(error){})
注意:POST請求傳參,不需要像GET請求那樣定義一個物件,在物件的params引數中傳參。post()方法的第二個引數物件,就是將來要傳遞的引數 。
配置
而在專案中,已經引入了axios,並且進行了簡單的封裝,在src下的http.js中:
import Vue from 'vue'
import axios from 'axios'
import config from './config'
// config中定義的基礎路徑是:http://api.leyou.com/api
axios.defaults.baseURL = config.api; // 設定axios的基礎請求路徑
axios.defaults.timeout = 3000; // 設定axios的請求時間
Vue.prototype.$http = axios;// 將axios賦值給Vue原型的$http屬性,這樣所有vue例項都可使用該物件
通過簡單封裝後,以後使用this.$http就可以發起相應的請求了。
2.4.2 QS工具
QS是一個第三方庫,即Query String,請求引數字串 。
什麼是請求引數字串?例如: name=jack&age=21
QS工具可以便捷的實現 JS的Object與QueryString的轉換。
通過this.$qs獲取這個工具。
為什麼要使用qs?
因為axios處理請求體的原則會根據請求資料的格式來定:
-
如果請求體是物件:會轉為json傳送
-
如果請求體是String:會作為普通表單請求傳送,但需要我們自己保證String的格式是鍵值對。
如:name=jack&age=12
所以在使用axios傳遞引數時,需要把json轉換成拼接好的字串。
2.4.3 增加分類
2.4.3.1 實現邏輯
首先將新新增的節點資訊存入資料庫,然後修改其父節點的相應資訊isParent = true
2.4.3.2 前端
在/pages/item/Category.vue中完善handleAdd方法,傳入的引數是node,即當前節點的詳細資訊,使用qs進行轉換,然後傳送請求。
handleAdd(node) {
this.$http({
method:'post',
url:'/item/category',
data:this.$qs.stringify(node)
}).then().catch();
}
2.4.3.3 後臺介面
Controller
-
請求方式:新增使用PostMapping
-
請求路徑:/api/item/category。其中/api是閘道器字首,/item是閘道器的路由對映,真實的路徑應該是/category
-
請求引數:節點引數(node)
-
返回值結果:如果新增成功就返回201 CREATED
/**
* 儲存
* @return
*/
@PostMapping
public ResponseEntity<Void> saveCategory(Category category){
System.out.println(category);
this.categoryService.saveCategory(category);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
Service
介面
/**
* 儲存
* @param category
*/
void saveCategory(Category category);
實現類
@Override
public void saveCategory(Category category) {
/**
* 將本節點插入到資料庫中
* 將此category的父節點的isParent設為true
*/
//1.首先置id為null
category.setId(null);
//2.儲存
this.categoryMapper.insert(category);
//3.修改父節點
Category parent = new Category();
parent.setId(category.getParentId());
parent.setIsParent(true);
this.categoryMapper.updateByPrimaryKeySelective(parent);
}
Mapper
依舊使用通用mapper提供的方法insert和updateByPrimaryKeySelective
2.4.4 刪除分類
2.4.4.1 實現邏輯
刪除比較麻煩一點,首先要確定被刪節點是父節點還是子節點。如果是父節點,那麼刪除所有附帶子節點,然後要維護中間表。如果是子節點,那麼只刪除自己,然後判斷父節點孩子的個數,如果不為0,則不做任何修改;如果為0,則修改父節點isParent的值為false,最後維護中間表。
中間表:tb_category_brand。是用來維護分類和品牌的對應關係的,一個分類下會有多個品牌,某個品牌可能屬於不同的分類。所以中間表中儲存的資料就是category_id和brand_id,而且category_id中儲存的是最底一層的類目id,也就是分類的葉子節點id。
當對中間表進行修改的時候,那麼就需要找出當前節點下所有的葉子節點(如果是父節點),然後刪除中間表中的對應資料。
2.4.4.2 前端
在/pages/item/Category.vue中完善handleDelete方法,傳入引數是要刪除的節點id,然後傳送請求。
handleDelete(id) {
console.log("delete ... " + id)
this.$http.delete("/item/category/cid/"+id).then(() =>{
this.$message.info("刪除成功!");
}).catch(() =>{
this.$message.info("刪除失敗!");
})
}
2.4.4.3 後端
Controller
-
請求方式:刪除使用DeleteMapping
-
請求路徑:/api/item/category/cid/{cid}。其中/api是閘道器字首,/item是閘道器的路由對映,真實的路徑應該是/category/cid/{cid}
-
請求引數:請求引數為cid,使用@PathVariable("cid")獲取
-
返回值結果:如果新增成功就返回200 OK
/**
* 刪除
* @return
*/
@DeleteMapping("cid/{cid}")
public ResponseEntity<Void> deleteCategory(@PathVariable("cid") Long id){
this.categoryService.deleteCategory(id);
return ResponseEntity.status(HttpStatus.OK).build();
}
Service
介面
/**
* 刪除
* @param id
*/
void deleteCategory(Long id);
實現類
@Override
public void deleteCategory(Long id) {
Category category=this.categoryMapper.selectByPrimaryKey(id);
if(category.getIsParent()){
//1.查詢所有葉子節點
List<Category> list = new ArrayList<>();
queryAllLeafNode(category,list);
//2.查詢所有子節點
List<Category> list2 = new ArrayList<>();
queryAllNode(category,list2);
//3.刪除tb_category中的資料,使用list2
for (Category c:list2){
this.categoryMapper.delete(c);
}
//4.維護中間表
for (Category c:list){
this.categoryMapper.deleteByCategoryIdInCategoryBrand(c.getId());
}
}else {
//1.查詢此節點的父親節點的孩子個數 ===> 查詢還有幾個兄弟
Example example = new Example(Category.class);
example.createCriteria().andEqualTo("parentId",category.getParentId());
List<Category> list=this.categoryMapper.selectByExample(example);
if(list.size()!=1){
//有兄弟,直接刪除自己
this.categoryMapper.deleteByPrimaryKey(category.getId());
//維護中間表
this.categoryMapper.deleteByCategoryIdInCategoryBrand(category.getId());
}
else {
//已經沒有兄弟了
this.categoryMapper.deleteByPrimaryKey(category.getId());
Category parent = new Category();
parent.setId(category.getParentId());
parent.setIsParent(false);
this.categoryMapper.updateByPrimaryKeySelective(parent);
//維護中間表
this.categoryMapper.deleteByCategoryIdInCategoryBrand(category.getId());
}
}
}
分析:
- 先判斷此節點是否是父節點
- 如果是,則:
- 需要一個可以查詢所有葉子節點的函式queryAllLeafNode,引數有兩個,一個是父節點,另一個是用來接收子節點的list。
- 需要一個可以查詢所有子節點的函式queryAllNode,引數同上。
- 刪除tb_category中的資料直接使用通用mappper中的方法即可。
- 維護中間表tb_category_brand時,需要在mapper中自定義方法deleteByCategoryIdInCategoryBrand,根據category的id刪除對應的資料。
- 如果不是,則:
- 查詢此節點還有幾個兄弟節點
- 如果有兄弟,則直接刪除自己,維護中間表
- 如果沒有兄弟,先刪除自己,然後修改父節點的isParent為false,最後維護中間表
查詢子節點和葉子節點的函式:
/**
* 查詢本節點下所包含的所有葉子節點,用於維護tb_category_brand中間表
* @param category
* @param leafNode
*/
private void queryAllLeafNode(Category category,List<Category> leafNode){
if(!category.getIsParent()){
leafNode.add(category);
}
Example example = new Example(Category.class);
example.createCriteria().andEqualTo("parentId",category.getId());
List<Category> list=this.categoryMapper.selectByExample(example);
for (Category category1:list){
queryAllLeafNode(category1,leafNode);
}
}
/**
* 查詢本節點下所有子節點
* @param category
* @param node
*/
private void queryAllNode(Category category,List<Category> node){
node.add(category);
Example example = new Example(Category.class);
example.createCriteria().andEqualTo("parentId",category.getId());
List<Category> list=this.categoryMapper.selectByExample(example);
for (Category category1:list){
queryAllNode(category1,node);
}
}
Mapper
/**
* 根據category id刪除中間表相關資料
* @param cid
*/
@Delete("DELETE FROM tb_category_brand WHERE category_id = #{cid}")
void deleteByCategoryIdInCategoryBrand(@Param("cid") Long cid);
其他的方法都是通用mapper提供的:selectByPrimaryKey、delete、selectByExample、updateByPrimaryKeySelective、deleteByPrimaryKey
2.4.5 修改分類
2.4.5.1 實現邏輯
因為修改只能修改分類的名字,所以比較簡單,直接更新資料庫中對應id的name即可。
2.4.5.2 前端
在/pages/item/Category.vue中完善handleEdit方法,傳入的引數是id和name,即要修改的節點id及新的name,先構造一個json,然後使用qs進行轉換,最後傳送請求。
handleEdit(id,name) {
const node={
id:id,
name:name
}
this.$http({
method:'put',
url:'/item/category',
data:this.$qs.stringify(node)
}).then(() => {
this.$message.info("修改成功!");
}).catch(() => {
this.$message.info("修改失敗!");
});
}
需要注意的是專案中提供的tree元件在進行修改時會發生錯誤,原因是位於/src/components/tree/TreeItem.vue中,afterEdit方法中if條件中的判斷出了問題,應該是this.beginEdit,而不是this.model.beginEdit。
afterEdit() {
if (this.beginEdit) {
this.beginEdit = false;
this.handleEdit(this.model.id, this.model.name);
}
}
2.4.5.3 後端
Controller
-
請求方式:修改使用PutMapping
-
請求路徑:/api/item/category。其中/api是閘道器字首,/item是閘道器的路由對映,真實的路徑應該是/category
-
請求引數:節點引數(node)
-
返回值結果:如果新增成功就返回202 ACCEPTED
/**
* 更新
* @return
*/
@PutMapping
public ResponseEntity<Void> updateCategory(Category category){
this.categoryService.updateCategory(category);
return ResponseEntity.status(HttpStatus.ACCEPTED).build();
}
Service
介面
/**
* 更新
* @param category
*/
void updateCategory(Category category);
實現類
@Override
public void updateCategory(Category category) {
this.categoryMapper.updateByPrimaryKeySelective(category);
}
Mapper
依舊使用通用mapper中的updateByPrimaryKeySelective方法。
三、效果展示
四、遇到的問題
4.1 分類增加的時候發生的問題
- 增加的邏輯:構造一個新節點,然後將這個新節點插入到”樹“中。那麼新節點的資料為:
- 自定義元件中新增節點程式碼(/src/components/tree/TreeItem.vue):
addChild: function () {
let child = {
id: 0,
name: '新的節點',
parentId: this.model.id,
isParent: false,
sort:this.model.children? this.model.children.length + 1:1
}
if (!this.model.isParent) {
Vue.set(this.model, 'children', [child]);
this.model.isParent = true;
this.open = true;
this.handleAdd(child);
} else {
if (!this.isFolder) {
this.$http.get(this.url, {params: {pid: this.model.id}}).then(resp => {
Vue.set(this.model, 'children', resp.data);
this.model.children.push(child);
this.open = true;
this.handleAdd(child);
});
} else {
this.model.children.push(child);
this.open = true;
this.handleAdd(child);
}
}
}
- 問題場景
假設在圖書、音像、電子書刊分類下新增一個分類名為Node1。點選新增按鈕,然後修改名字為Node1。此時這個節點已經插入到資料庫中,但是這個節點的資訊在新增完畢後並沒有同步到前端頁面當中,所以當前節點的id = 0。那麼,以Node1作為父節點,在新增子節點時就會產生問題,因為Node1的id沒有同步,一直是0,所以在建立它的子節點時,子節點的parentId就為0了,即發生新增失敗。
4.2 解決方法
最好的解決方法就是:當新增完畢後,重新整理一下tree元件中的資料,而且必須保證樹的展開層次與重新整理前一致。但是由於對Vue並不是很熟悉,tree這個元件只是初步掌握,這種方法沒有實現。
笨辦法:因為資料庫中tb_category這個表的id欄位是自增的,所以在新增前可以獲取資料庫中最後一條資料的id,在構造新節點時,給id賦的值就是最後一條資料的id加1。
同時對增加功能進行優化,必須在選中(即必須點選父節點)的情況下才能進行新增。
4.2.1 前端程式碼修改
先發送請求獲取資料庫中最後一條記錄,然後得到id,構造新節點,插入。
addChild: function () {
this.$http.get(this.url,{params: {pid:-1}}).then(resp => {
let child = {
id: resp.data[0].id+1,
name: '新的節點',
parentId: this.model.id,
isParent: false,
sort:this.model.children? this.model.children.length + 1:1
};
if (this.isSelected) {
if (!this.model.isParent) {
Vue.set(this.model, 'children', [child]);
this.model.isParent = true;
this.open = true;
this.handleAdd(child);
} else {
if (!this.isFolder) {
this.$http.get(this.url, {params: {pid: this.model.id}}).then(resp => {
Vue.set(this.model, 'children', resp.data);
this.model.children.push(child);
this.open = true;
this.handleAdd(child);
});
} else {
this.model.children.push(child);
this.open = true;
this.handleAdd(child);
}
}
}else {
this.$message.error("選中後再操作!");
}
});
},
4.2.2 後端程式碼修改
Controller
修改原來的queryCategoryByPid方法,當傳入的id為-1時,查詢最後一條資料,否則根據實際id查詢。
@GetMapping("/list")
public ResponseEntity<List<Category>> queryCategoryByPid(@RequestParam("pid") Long pid){
//如果pid的值為-1那麼需要獲取資料庫中最後一條資料
if (pid == -1){
List<Category> last = this.categoryService.queryLast();
return ResponseEntity.ok(last);
}
else {
List<Category> list = this.categoryService.queryCategoryByPid(pid);
if (list == null) {
//沒有找到返回404
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
//找到返回200
return ResponseEntity.ok(list);
}
}
Service
介面
/**
* 查詢當前資料庫中最後一條資料
* @return
*/
List<Category> queryLast();
實現類
/**
* 查詢資料庫中最後一條資料
* @return
*/
@Override
public List<Category> queryLast() {
List<Category> last =this.categoryMapper.selectLast();
return last;
}
Mapper
提供查詢最後一條資料的方法
/**
* 查詢最後一條資料
* @return
*/
@Select("SELECT * FROM `tb_category` WHERE id = (SELECT MAX(id) FROM tb_category)")
List<Category> selectLast();