Vue多表案例(一)

注:由于此案例设计的代码较多,所以分为两个部分来上传。此文章为第一部分。

1.准备工作

1.1数据库

# 创建分类表 t_category , 主键,主表(1表)
CREATE TABLE t_category(
  cid INT PRIMARY KEY AUTO_INCREMENT,
  cname VARCHAR(50)
);
# 创建书籍表 t_book , 外键,从表(多表)
CREATE TABLE t_book(
  bid INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(50),
  price DOUBLE(6,2),	#9999.99
  category_id INT 	#外键
);

# 使用主外键约束,描述一对多关系
ALTER TABLE t_book ADD CONSTRAINT FOREIGN KEY(category_id) REFERENCES t_category (cid);

# 插入若干条书籍
INSERT INTO t_category(cid,cname) VALUES(1,'小说');
INSERT INTO t_category(cid,cname) VALUES(2,'玄幻');
INSERT INTO t_category(cid,cname) VALUES(3,'人物传记');
INSERT INTO t_book(bid,title,price,category_id) VALUES(1,'坏蛋是怎么练成的',99.9,1);
INSERT INTO t_book(bid,title,price,category_id) VALUES(2,'武将是怎么练成的',99.9,1);
INSERT INTO t_book(bid,title,price,category_id) VALUES(3,'斗破苍穹',99.9,2);
INSERT INTO t_book(bid,title,price,category_id) VALUES(4,'凡人修仙传',99.9,2);
INSERT INTO t_book(bid,title,price,category_id) VALUES(5,'仙逆',99.9,2);
INSERT INTO t_book(bid,title,price,category_id) VALUES(6,'了不起的张焰烽',99.9,3);
INSERT INTO t_book(bid,title,price,category_id) VALUES(7,'田企锐那些年',99.9,3);
INSERT INTO t_book(bid,title,price,category_id) VALUES(8,'谢明安幸福生活III',99.9,3);

1.2后端:环境搭建

1.2.1创建项目

步骤一:使用Spring脚手架创建maven项目

1.2.2项目配置

步骤三:修改pom.xml文件,添加依赖

<!--确定spring boot的版本-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.9.RELEASE</version>
</parent>
<dependencies>
    <!--web起步依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--通用mapper起步依赖-->
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.0.4</version>
    </dependency>
    <!--MySQL数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--mybatis分页插件-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.3</version>
    </dependency>

步骤四:创建 application.properties文件,配置数据库

#Tomcat
server.port=8090
#DB configuration
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/vue02?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
#druid
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true

1.2.3工具类

步骤六:创建全局跨域配置类 GlobalCorsConfig.java
Vue多表案例(一)

package com.czxy.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 yxq
 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("*");
        //是否发送Cookie信息
        config.setAllowCredentials(true);
        //放行哪些原始域(请求方式)
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");     //get
        config.addAllowedMethod("PUT");     //put
        config.addAllowedMethod("POST");    //post
        config.addAllowedMethod("DELETE");  //delete
        config.addAllowedMethod("PATCH");
        config.addAllowedHeader("*");
        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

1.3分类模块:基本架构

步骤一:创建Java Category和Book
Vue多表案例(一)

package com.czxy.domain;

import java.io.Serializable;
import java.util.List;
import javax.persistence.*;

@Table(name = "t_category")
public class TCategory implements Serializable {
    @Id
    @Column(name = "cid")
    @GeneratedValue(generator = "JDBC")
    private Integer cid;

    @Column(name = "cname")
    private String cname;

    private List<TBook> list;

    private static final long serialVersionUID = 1L;

    public List<TBook> getList() {
        return list;
    }

    public void setList(List<TBook> list) {
        this.list = list;
    }

    /**
     * @return cid
     */
    public Integer getCid() {
        return cid;
    }

    /**
     * @param cid
     */
    public void setCid(Integer cid) {
        this.cid = cid;
    }

    /**
     * @return cname
     */
    public String getCname() {
        return cname;
    }

    /**
     * @param cname
     */
    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", cid=").append(cid);
        sb.append(", cname=").append(cname);
        sb.append("]");
        return sb.toString();
    }
}
package com.czxy.domain;

import java.io.Serializable;
import javax.persistence.*;

@Table(name = "t_book")
public class TBook implements Serializable {
    @Id
    @Column(name = "bid")
    @GeneratedValue(generator = "JDBC")
    private Integer bid;

    @Column(name = "title")
    private String title;

    @Column(name = "price")
    private Double price;

    @Column(name = "category_id")
    private Integer categoryId;

    private static final long serialVersionUID = 1L;

    /**
     * @return bid
     */
    public Integer getBid() {
        return bid;
    }

    /**
     * @param bid
     */
    public void setBid(Integer bid) {
        this.bid = bid;
    }

    /**
     * @return title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @param title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return price
     */
    public Double getPrice() {
        return price;
    }

    /**
     * @param price
     */
    public void setPrice(Double price) {
        this.price = price;
    }

    /**
     * @return category_id
     */
    public Integer getCategoryId() {
        return categoryId;
    }

    /**
     * @param categoryId
     */
    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", bid=").append(bid);
        sb.append(", title=").append(title);
        sb.append(", price=").append(price);
        sb.append(", categoryId=").append(categoryId);
        sb.append("]");
        return sb.toString();
    }
}

步骤二:创建CategoryMapper
Vue多表案例(一)

package com.czxy.dao;

import com.czxy.domain.TCategory;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TCategoryMapper extends tk.mybatis.mapper.common.Mapper<TCategory> {
}

步骤三:创建CategoryService
Vue多表案例(一)

package com.czxy.service;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.czxy.dao.TCategoryMapper;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TCategoryService{

    @Resource
    private TCategoryMapper tCategoryMapper;

}

步骤四:CategoryController
Vue多表案例(一)

package com.czxy.controller;

import com.czxy.service.TCategoryService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private TCategoryService categoryService;

}

1.5前端:环境搭建

1.5.1构建项目

创建项目
vue create vue1025
Vue多表案例(一)
启动项目
Vue多表案例(一)

1.5.2布局

修改App.vue文件,完成页面布局

<template>
  <div id="app">
    <router-link to="/categoryList">分类管理</router-link>&nbsp;&nbsp;&nbsp;&nbsp;
    <router-link to="/bookList">书籍管理</router-link>&nbsp;&nbsp;&nbsp;&nbsp;
    <hr />
    <!-- 组件显示位置 -->
    <router-view />
  </div>
</template>


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

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

Vue多表案例(一)

2.分类模块

2.1查询所有

2.1.1后端

步骤一:修改CategoryService

package com.czxy.service;

import com.czxy.domain.TCategory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.czxy.dao.TCategoryMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TCategoryService{

    @Resource
    private TCategoryMapper tCategoryMapper;
    
    public List<TCategory> findAll(){
        return tCategoryMapper.selectAll();
    }
    
}

步骤二:修改CategoryController

package com.czxy.controller;

import com.czxy.domain.TCategory;
import com.czxy.service.TCategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private TCategoryService tCategoryService;
    @GetMapping
    public ResponseEntity<List<TCategory>> findAll(){
        List<TCategory> list = tCategoryService.findAll();
        return ResponseEntity.ok(list);
    }
}

2.1.2前端

Vue多表案例(一)
前提:安装axios

npm install axios

步骤一:创建 src/views/CategoryList.vue文件
Vue多表案例(一)

步骤二:修改 src/router/index.js文件
Vue多表案例(一)
步骤三:修改CategoryList.vue,页面加载成功,发送ajax查询所有分类

<script>
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8090"

export default {
    data(){
        return{
            categorys:[]
        }
    },
    created(){
        axios.get("/category").then(res => {
            this.categorys = res.data
        })
    }    
}
</script>

步骤四:修改CategoryList.vue,data区域存放数据,展示数据

<template>
  <div>
    <table border="1">
      <tr>
        <th>编号</th>
        <th>分类名字</th>
        <th>操作</th>
      </tr>
      <tr v-for="(category,index) in categorys" :key="index">
          <td>{{category.cid}}</td>
          <td>{{category.cname}}</td>
          <td>
              新增
              修改
              删除
          </td>
      </tr>
    </table>
  </div>
</template>

2.2添加分类

2.2.1后端

步骤一:修改CategoryService,添加save方法

package com.czxy.service;

import com.czxy.domain.TCategory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.czxy.dao.TCategoryMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TCategoryService{

    @Resource
    private TCategoryMapper tCategoryMapper;

    public List<TCategory> findAll(){
        return tCategoryMapper.selectAll();
    }
    
    public void addCategory(TCategory tCategory){
        tCategoryMapper.insert(tCategory);
    }

}

步骤二:修改CategoryController,添加save方法

package com.czxy.controller;

import com.czxy.domain.TCategory;
import com.czxy.service.TCategoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private TCategoryService tCategoryService;

    @GetMapping
    public ResponseEntity<List<TCategory>> findAll(){
        List<TCategory> list = tCategoryService.findAll();
        return ResponseEntity.ok(list);
    }
    
    @PostMapping
    public ResponseEntity<Void> addCategory(@RequestBody TCategory tCategory){
        tCategoryService.addCategory(tCategory);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

}


2.2.2前端

Vue多表案例(一)
Vue多表案例(一)
Vue多表案例(一)
步骤一:修改CategoryList.vue页面,添加“新增”按钮

<template>
  <div>
    <table border="1">
      <tr>
        <th>编号</th>
        <th>分类名字</th>
        <th>操作</th>
      </tr>
      <tr v-for="(category,index) in categorys" :key="index">
          <td>{{category.cid}}</td>
          <td>{{category.cname}}</td>
          <td>
              <router-link to="/categoryAdd">新增</router-link>
              修改
              删除
          </td>
      </tr>
    </table>
  </div>
</template>

步骤二:创建CategoryAdd.vue页面
Vue多表案例(一)
步骤三:修改路由 router/index.js,添加路由
Vue多表案例(一)
步骤四:修改CategoryAdd.vue页面,提供表单,并绑定对象

<template>
  <div>
    <table>
      <tr>
        <td>分类名字</td>
        <td><input type="text" v-model="category.cname"></td>
      </tr>
      <tr>
        <td colspan="2"><input type="button" value="新增" ></td>
      </tr>
    </table>
  </div>
</template>
<script>
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8080"
export default {
  data() {
    return {
      category:{}
    }
  }
}
</script>
<style scoped>

</style>

步骤五:修改CategoryAdd.vue页面,点击“添加”按钮发送ajax请求

<template>
  <div>
    <table>
      <tr>
        <td>分类名字</td>
        <td><input type="text" v-model="category.cname"></td>
      </tr>
      <tr>
        <td colspan="2"><input type="button" value="新增" @click="categoryAdd()"></td>
      </tr>
    </table>
  </div>
</template>
<script>
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8090"
export default {
  data() {
    return {
      category:{}
    }
  },
  methods: {
    categoryAdd(){
      axios.post("/category",this.category).then(res => {
        alert("新增成功")
        this.$router.push("/categoryList")
      })
    }
  },
}
</script>
<style scoped>

</style>

2.3修改分类

2.3.1后端

步骤一:修改CategoryService,添加update方法

package com.czxy.service;

import com.czxy.domain.TCategory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.czxy.dao.TCategoryMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TCategoryService{

    @Resource
    private TCategoryMapper tCategoryMapper;

    public List<TCategory> findAll(){
        return tCategoryMapper.selectAll();
    }

    public void addCategory(TCategory tCategory){
        tCategoryMapper.insert(tCategory);
    }

    public TCategory findById(Integer cid) {
        return tCategoryMapper.selectByPrimaryKey(cid);
    }

    public void update(TCategory category) {
        tCategoryMapper.updateByPrimaryKey(category);
    }

}

步骤二:修改CategoryController,添加update方法

package com.czxy.controller;

import com.czxy.domain.TCategory;
import com.czxy.service.TCategoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private TCategoryService tCategoryService;

    @GetMapping
    public ResponseEntity<List<TCategory>> findAll(){
        List<TCategory> list = tCategoryService.findAll();
        return ResponseEntity.ok(list);
    }

    @PostMapping
    public ResponseEntity<Void> addCategory(@RequestBody TCategory tCategory){
        tCategoryService.addCategory(tCategory);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

    @GetMapping("/{cid}")
    public ResponseEntity<TCategory> findById(@PathVariable("cid") Integer cid){
        TCategory category = tCategoryService.findById(cid);
        return ResponseEntity.ok(category);
    }

    @PutMapping
    public ResponseEntity<String> update(@RequestBody TCategory category){
        TCategoryService.update(category);
        return ResponseEntity.ok("更新成功");
    }

}


2.3.2前端

步骤一:修改CategoryList.vue页面,给“修改”添加路径
Vue多表案例(一)
Vue多表案例(一)
Vue多表案例(一)

<template>
  <div>
    <table border="1">
      <tr>
        <th>编号</th>
        <th>分类名字</th>
        <th>操作</th>
      </tr>
      <tr v-for="(category,index) in categorys" :key="index">
        <td>{{category.cid}}</td>
        <td>{{category.cname}}</td>
        <td>
          <router-link to="/categoryAdd">新增</router-link>
          <router-link :to="'/categoryUpdate/' + category.cid">修改</router-link>
          删除
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
import axios from "axios";
axios.defaults.baseURL = "http://localhost:8090";

export default {
  data() {
    return {
      categorys: []
    };
  },
  created() {
    axios.get("/category").then(res => {
      this.categorys = res.data;
    });
  }
};
</script>

步骤二:创建CategoryUpdate.vue页面
Vue多表案例(一)

步骤三:修改 router/index.js,配置路由路径
Vue多表案例(一)
步骤四:修改CategoryUpdate.vue 文件,页面加载成功后,查询详情

<template>
  <div>
      <table border="1">
          <tr>
              <td>分类名称</td>
              <td><input type="text" v-model="category.cname"></td>
          </tr>
          <tr>
              <td></td>
              <td><input type="button" value="更新"></td>
          </tr>
      </table>
  </div>
</template>

<script>
// 1.1 导入axios组件
import axios from 'axios'
// 1.2 设置基本路径
axios.defaults.baseURL='http://localhost:8080'
export default {
    data() {
        return {
            category: {}
        }
    },
    created() {
        let cid = this.$route.params.cid
        axios.get('/category/' + cid).then( response => {
            this.category = response.data
            console.info(response.data)
        })
    },
}
</script>

<style>

</style>

步骤五:修改CategoryUpdate.vue 文件,完成更新操作

<template>
  <div>
    <table border="1">
      <tr>
        <td>分类名称</td>
        <td>
          <input type="text" v-model="category.cname" />
        </td>
      </tr>
      <tr>
        <td></td>
        <td>
          <input type="button" value="更新" @click="categoryUpdate" />
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
// 1.1 导入axios组件
import axios from "axios";
// 1.2 设置基本路径
axios.defaults.baseURL = "http://localhost:8090";
export default {
  data() {
    return {
      category: {}
    };
  },
  methods: {
    categoryUpdate() {
      // 1.3 发送ajax
      axios
        .put("/category", this.category)
        .then(response => {
          alert(response.data);
          this.$router.push("/categoryList");
        })
        .catch(error => {
          console.info(error);
        });
    }
  },
  created() {
    let cid = this.$route.params.cid;
    axios.get("/category/" + cid).then(response => {
      this.category = response.data;
      console.info(response.data);
    });
  }
};
</script>

<style>
</style>

2.4删除分类

Vue多表案例(一)
Vue多表案例(一)
Vue多表案例(一)

2.4.1后端

如果某分类有书籍,不能被删除。
步骤一:修改BookMapper,添加 findAllWithCid()

package com.czxy.dao;

import com.czxy.domain.TBook;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface TBookMapper extends tk.mybatis.mapper.common.Mapper<TBook> {

    @Select("select * from t_book where category_id = #{cid}")
    public List<TBook> findAllWithCid(@Param("cid") Integer cid);

}

步骤二:修改CategoryService,实现delete方法

package com.czxy.service;

import com.czxy.dao.TBookMapper;
import com.czxy.domain.TBook;
import com.czxy.domain.TCategory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.czxy.dao.TCategoryMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TCategoryService{

    @Resource
    private TCategoryMapper tCategoryMapper;
    @Resource
    private TBookMapper tBookMapper;

    public List<TCategory> findAll(){
        return tCategoryMapper.selectAll();
    }

    public void addCategory(TCategory tCategory){
        tCategoryMapper.insert(tCategory);
    }

    public TCategory findById(Integer cid) {
        return tCategoryMapper.selectByPrimaryKey(cid);
    }

    public void update(TCategory category) {
        tCategoryMapper.updateByPrimaryKey(category);
    }
    
    public void delete(Integer cid){
        List<TBook> list = tBookMapper.findAllWithCid(cid);
        if (list != null && list.size() > 0){
            throw new RuntimeException("当前分类有" + list.size() + "本书在使用,请先删除!");
        }
        tCategoryMapper.deleteByPrimaryKey(cid);
    }

}

步骤三:修改CategoryController,添加delete方法

@RestController
@RequestMapping("/category")
public class CategoryController {

@Resource
private CategoryService categoryService;

@DeleteMapping("/{cid}")
public ResponseEntity<String> delete(@PathVariable("cid") Integer cid){
    try {
        categoryService.delete(cid);
        return ResponseEntity.ok("删除成功");
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.ok(e.getMessage());
    }
}

}

2.4.2前端

步骤一:修改CategoryList.vue,编写categoryDelete完成删除操作

<template>
  <div>
      <table border="1" width="400">
        <tr>
          <td>编号</td>
          <td>分类名称</td>
          <td>操作</td>
        </tr>
        <tr v-for="(category,index) in allCategory" :key="index">
          <td>{{index + 1}} </td>
          <td>{{category.cname}} </td>
          <td>
            查看详情
            <router-link :to="'/categoryUpdate/' + category.cid">修改</router-link>
            <a href="#" @click.prevent="categoryDelete(category.cid)">删除</a> 
          </td>
        </tr>
      </table>
      <router-link to="/categoryAdd">添加分类</router-link>
  </div>
</template>

<script>
// 1.1 导入axios组件
import axios from 'axios'
// 1.2 设置基本路径
axios.defaults.baseURL='http://localhost:8080'
export default {
  created() {
    // 1.3 页面加载成功后,发送ajax查询所有
    axios.get('/category').then( response => {
      this.allCategory = response.data
    })
  },
  data() {
    return {
      allCategory: []
    }
  },
  methods: {
    categoryDelete(cid){
      if(window.confirm('您确定要删除么?')){
        axios.delete('/category/' + cid).then( response => {
          alert(response.data)
        })
      }
    }
  },
}
</script>

<style>

</style>

当前页面不能刷新,采用provide / inject 来完成刷新
provide 父组件声明一个功能,
inject 后代组件,在任意位置,通过inject可以直接引入provide声明的内容

步骤二:修改App.vue页面
通过控制显示与隐藏完成内容的刷新
reload() --> 将状态修改false,修改生效后(this.$nextTick),立即将状态改成true
通过provide将reloa() 声明成所有后代组件都可以功能
在后代组件任意位置,通过inject:[‘reload’],引入父组件的功能,并通过 this.reload()直接调用

<template>
  <div id="app">
    <router-link to="/categoryList">分类管理</router-link> &nbsp;&nbsp;&nbsp;&nbsp;
    <router-link to="/bookList">书籍管理</router-link> &nbsp;&nbsp;&nbsp;&nbsp;
    <hr/>
    <!-- 组件显示位置 -->
    <router-view v-if="isRouterAlive"/>
  </div>
</template>

<script>
export default {
  provide () {      //允许父组件,向后代组件注入一个依赖。后代组件必须通过inject
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      isRouterAlive: true
    }
  },
  methods: {
    reload () {
      this.isRouterAlive = false
      // 在下次 DOM 更新循环结束之后执行延迟回调
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    }
  }
}
</script>

步骤三:修改 CategoryList.vue页面

<template>
  <div>
      <table border="1" width="400">
        <tr>
          <td>编号</td>
          <td>分类名称</td>
          <td>操作</td>
        </tr>
        <tr v-for="(category,index) in allCategory" :key="index">
          <td>{{index + 1}} </td>
          <td>{{category.cname}} </td>
          <td>
            查看详情
            <router-link :to="'/categoryUpdate/' + category.cid">修改</router-link>
            <a href="#" @click.prevent="categoryDelete(category.cid)">删除</a> 
          </td>
        </tr>
      </table>
      <router-link to="/categoryAdd">添加分类</router-link>
  </div>
</template>

<script>
// 1.1 导入axios组件
import axios from 'axios'
// 1.2 设置基本路径
axios.defaults.baseURL='http://localhost:8080'
export default {
  inject:['reload'],
  created() {
    // 1.3 页面加载成功后,发送ajax查询所有
    axios.get('/category').then( response => {
      this.allCategory = response.data
    })
  },
  data() {
    return {
      allCategory: []
    }
  },
  methods: {
    categoryDelete(cid){
      if(window.confirm('您确定要删除么?')){
        axios.delete('/category/' + cid).then( response => {
          alert(response.data)
          this.reload()
        })
      }
    }
  },
}
</script>

<style>

</style>
Vue多表案例(一)Vue多表案例(一) Java_cfx 发布了1 篇原创文章 · 获赞 0 · 访问量 67 私信 关注
上一篇:关于博客园内嵌入bilibili视频


下一篇:kubernetes入门(06)kubernetes的核心概念(3)