Maynor teaches you to complete a SPA commodity management system implemented by SpringBoot+Vue+Element (add, delete, modify and check)

Posted by Snart on Fri, 05 Nov 2021 04:36:10 +0100

Maynor teaches you to complete a SPA commodity management system implemented by SpringBoot+Vue+Element (add, delete, modify and check)

preface

I will get the complete code by private mail after three links~
I have completed the SPA commodity management system all morning. Please connect three times!

Station B demo video

Maynor teaches you to complete a SpringBoot+Vue+Element demonstration video (there is a little bug at the end)_ Beep beep beep_ bilibili

Project requirements

Commodity management system

1. Product list

Multi criteria query includes fuzzy query, interval query, category selection and brand selection, list pagination, category and category drop-down list selection

2. Add item

3. Modify product

4. Batch delete

5. Single item deletion

Project construction:

Construction of springboot project (your first springboot project)_ A coder CSDN blog_ springboot project

Project structure

Back end structure

configuration file

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!-- Unified version maintenance -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mybatis.starter.version>1.3.2</mybatis.starter.version>
        <mapper.starter.version>2.0.2</mapper.starter.version>
        <mysql.version>5.1.32</mysql.version>
        <pageHelper.starter.version>1.2.5</pageHelper.starter.version>
        <durid.starter.version>1.1.10</durid.starter.version>
        <lombok.version>1.18.16</lombok.version>
    </properties>

    <dependencies>
        <!-- SpringBoot integration SpringMVC Starter for -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- SpringBoot integration jdbc Initiator for and transactions -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- mybatis starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.starter.version}</version>
        </dependency>
        <!-- currency Mapper starter -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>${mapper.starter.version}</version>
        </dependency>
        <!-- Paging assistant launcher -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pageHelper.starter.version}</version>
        </dependency>
        <!-- mysql drive -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- Druid Connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${durid.starter.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

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/test3?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
#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
logging.level.com.czxy=debug

Encapsulation class

BaseResult

package com.czxy.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.ResponseEntity;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseResult {

    /**
     * 10000 success
     * 10001 fail
     */
    private Integer code;
    /**
     * Success or failure message reminder
     */
    private String msg;
    /**
     * data
     */
    private Object data;

    private Integer total;

    public BaseResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static ResponseEntity<BaseResult> success(Object data){
        return ResponseEntity.ok(new BaseResult(10000,"success",data));
    }

    public static ResponseEntity<BaseResult> fail(){
        return ResponseEntity.ok(new BaseResult(10001,"fail",null));
    }

    public static ResponseEntity<BaseResult> success(Object data,Integer total){
        return ResponseEntity.ok(new BaseResult(10000,"success",data,total));
    }

}

GlobalCorsConfig

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;


/**  Global cross domain configuration class
 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1. Add CORS configuration information
        CorsConfiguration config = new CorsConfiguration();
        //Which original domains are released
        config.addAllowedOrigin("*");
        //Send Cookie information
        config.setAllowCredentials(false);
        //Which original domains are released (request method)
        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. Add mapping path
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3. Return to the new CorsFilter
        return new CorsFilter(configSource);
    }

}

database

-- MySQL dump 10.13  Distrib 5.5.15, for Win64 (x86)
--
-- Host: 127.0.0.1    Database: test3
-- ------------------------------------------------------
-- Server version	5.5.15

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `brand`
--

DROP TABLE IF EXISTS `brand`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `brand` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `brand`
--

LOCK TABLES `brand` WRITE;
/*!40000 ALTER TABLE `brand` DISABLE KEYS */;
INSERT INTO `brand` VALUES (1,'dandy'),(2,'Tang Shi'),(4,'Taiping bird'),(5,'Senma'),(6,'Big billed monkey'),(7,'adidas'),(8,'Nike'),(9,'Apple'),(10,'Huawei'),(11,'millet'),(12,'GREE');
/*!40000 ALTER TABLE `brand` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `category`
--

DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `category`
--

LOCK TABLES `category` WRITE;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` VALUES (1,'Women's wear'),(2,'men's wear'),(3,'Underwear'),(4,'household electrical appliances'),(5,'Vacuum cleaner'),(6,'Heater'),(7,'mobile phone'),(8,'Home textiles');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `goods`
--

DROP TABLE IF EXISTS `goods`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `goods` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `brand_id` int(11) DEFAULT NULL,
  `category_id` int(11) DEFAULT NULL,
  `introduction` varchar(50) DEFAULT NULL,
  `store_num` int(11) DEFAULT NULL,
  `price` double DEFAULT NULL,
  `create_time` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `goods`
--

LOCK TABLES `goods` WRITE;
/*!40000 ALTER TABLE `goods` DISABLE KEYS */;
INSERT INTO `goods` VALUES (2,'Huawei Mate30',10,7,'Huawei MATE30 Golden 1 T',200,9999,'2021-10-22'),(8,'sneakers',8,1,'Versatile fashion casual shoes',6000,999,'2021-11-02'),(9,'Jacket',4,2,'New camouflage casual hooded top',8888,789,'2021-11-01'),(10,'demo',NULL,NULL,'xxxx',1,999,'2021-11-03'),(11,'1',NULL,NULL,'1',111,11,NULL),(12,'2',NULL,NULL,NULL,222,22,'2021-11-25T16:00:00.000Z'),(13,'123',NULL,NULL,'123',12,123,'2021-11-09');
/*!40000 ALTER TABLE `goods` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2021-11-05  9:27:52

Back end code part

It mainly completes the development of entity/dao/service/controller/vo. Due to repeated code, only the complete code of Goods is posted

entity layer:

@Table(name = "goods")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class TTeacher implements Serializable {
	//id
//	name
//			brand_id
//	category_id
//			introduction
//	store_num
//			price
//	create_time
    @Id
	private Integer id;
	private String name;
	private Integer brand_id;
	private Integer category_id;
	private String introduction;
	private Integer store_num;
	private Double price;
	private String create_time;
	// As long as the date type in java complies with February 2, 2012
	private TSchool school;
	private TType type;

}

dao layer:

@org.apache.ibatis.annotations.Mapper
public interface TeacherMapper extends Mapper<TTeacher> {

}

service layer:

public interface TeacherService {
    ResponseEntity<BaseResult> findByCondition(TeacherSearchVO teacherSearchVO);

    boolean add(TTeacher tea);

    TTeacher findById(Integer id);

    boolean update(TTeacher tea);

    boolean deleteById(Integer id);

    List<TTeacher> selectAll();
}

impl implementation class

@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Override
    public ResponseEntity<BaseResult> findByCondition(TeacherSearchVO teacherSearchVO) {
       // List<TTeacher> teaList = new ArrayList<>();// Finally, the data to be returned to the front end
        //Splicing conditions
        String teacherName = teacherSearchVO.getTeacherName();
        Integer schoolId = teacherSearchVO.getSchoolId();
        Integer typeId = teacherSearchVO.getTypeId();
        String typeName = teacherSearchVO.getTypeName();

        Integer minSalary = teacherSearchVO.getMinSalary();
        Integer maxSalary = teacherSearchVO.getMaxSalary();
        Integer page = teacherSearchVO.getPage();
        Integer rows = teacherSearchVO.getRows();

        Example example = new Example(TTeacher.class);
        Example.Criteria criteria = example.createCriteria();
        //1 vague name
        if (StringUtils.isNotBlank(teacherName)){
            criteria.andLike("name","%"+teacherName+"%");
        }
        //2. ID exact matching
        if (schoolId!=null&&StringUtils.isNotBlank(schoolId.toString())){
            criteria.andEqualTo("brand_id",schoolId);
        }

        if (typeId!=null&&StringUtils.isNotBlank(typeId.toString())){
            criteria.andEqualTo("category_id",typeId);
        }
        if (minSalary!=null&&StringUtils.isNotBlank(minSalary.toString())){
            criteria.andGreaterThanOrEqualTo("price",minSalary);
        }
        //4
        if (maxSalary!=null&&StringUtils.isNotBlank(maxSalary.toString())){
            criteria.andLessThanOrEqualTo("price",maxSalary);
        }
        //Find the total number of entries for paging
        int total = teacherMapper.selectByExample(example).size();

        //7 back end paging
        PageHelper.startPage(page,rows);

        //8 detection results
        List<TTeacher> teacherList = teacherMapper.selectByExample(example);

        //Backend Association id display name
        for (TTeacher tea:teacherList){
            tea.setType(typeMapper.selectByPrimaryKey(tea.getCategory_id()));
            tea.setSchool(schoolMapper.selectByPrimaryKey(tea.getBrand_id()));
        }

        if (teacherList.size()==0&&teacherSearchVO.getPage()!=1){
            page = total%rows==0?total/rows:(total/rows+1);
            teacherSearchVO.setPage(page);
            findByCondition(teacherSearchVO);
        }

        return BaseResult.success(teacherList,total);
    }

    @Override
    public boolean add(TTeacher tea) {
        return teacherMapper.insert(tea)==1;
    }

    @Override
    public TTeacher findById(Integer id) {
        return teacherMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean update(TTeacher tea) {
        return teacherMapper.updateByPrimaryKey(tea)==1;
    }


    @Override
    public boolean deleteById(Integer id) {
        return teacherMapper.deleteByPrimaryKey(id)==1;
    }

    @Override
    public List<TTeacher> selectAll() {
        return teacherMapper.selectAll();
    }
}

VO class:

@Data
public class TeacherSearchVO {

    private String teacherName;
    private String typeName;
    private Integer schoolId;
    private Integer typeId;
    private Integer minSalary;
    private Integer maxSalary;
    private Integer page;//Page number
    private Integer rows;//Number of rows

}

controller layer:

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherServiceImpl teacherService;

    @GetMapping("/condition")
    public ResponseEntity<BaseResult> findByCondition(TeacherSearchVO teacherSearchVO){
        ResponseEntity<BaseResult> rbr = teacherService.findByCondition(teacherSearchVO);
        return rbr;
    }

    @GetMapping("/all")
    public List<TTeacher> selectAll( ){
        List<TTeacher>  rbr = teacherService.selectAll();
        return rbr;
    }

    @PostMapping
    public ResponseEntity<BaseResult> add(@RequestBody TTeacher tea){
        boolean flag = teacherService.add(tea);
        if (flag){
            return BaseResult.success("Successfully added");
        }else{
            return BaseResult.fail();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<BaseResult> findById(@PathVariable("id") Integer id){
        TTeacher tea = teacherService.findById(id);
        return BaseResult.success(tea);
    }
    @PutMapping
    public ResponseEntity<BaseResult> update(@RequestBody TTeacher tea){
        boolean flag = teacherService.update(tea);
        if (flag){
            return BaseResult.success("Modified successfully");
        }else{
            return BaseResult.fail();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<BaseResult> deleteById(@PathVariable Integer id){
        boolean flag= teacherService.deleteById(id);
        if (flag){
            return BaseResult.success("Delete succeeded");
        }else{
            return BaseResult.fail();
        }
    }
    @DeleteMapping("/batchDelete/{ids}")
    public ResponseEntity<BaseResult> bachDelete(@PathVariable String ids){
        String[] splitIds = ids.split(",");
        for (String id:splitIds){
            teacherService.deleteById(Integer.parseInt(id));
        }
        return BaseResult.success("Delete succeeded");
    }

}

Maynor whispered bb: the back-end is completed. Next, let's move to the implementation of the front-end page!

Front end code:

vue create command:

npm create xxx

cd xxx

npm run serve

vue installation command:

npm install

elementui installation

npm i element-ui -S

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8090"
Vue.prototype.$http = axios

Vue.use(ElementUI)



Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <div id="nav">
      
      <!-- <router-link to="/schoolList">Brand list</router-link> | -->
      <router-link to="/teacherList">Commodity management</router-link>
    </div>
    <router-view/>
  </div>
</template>

index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/schoolList',
    name: 'SchoolList',
    component: () => import('@/views/SchoolList.vue')
  },
  {
    path: '/teacherList',
    name: 'TeacherList',
    component: () => import('@/views/TeacherList.vue')
  },
  {
    path: '/addTeacher',
    name: 'AddTeacher',
    component: () => import('@/views/AddTeacher.vue')
  },
  {
    path: '/updateTeacher/:id(\\d+)',
    name: 'UpdateTeacher',
    component: () => import('@/views/UpdateTeacher.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

Front end addition, deletion, modification and query

Page display

 <div>
       <hr>
      <router-link to="/addTeacher">New products</router-link>   
      <br>
      <input type="button" value="search" @click="initTeaList()"> <br>
      <input type="button" value="Batch delete" @click="batchDelete()">
      <br>
      brand:<select v-model="teacherSearchVo.schoolId">
               <option value="">--Please select a brand--</option>
               <option v-for="(s,index) in schoolList" :key="index" :value="s.id">{{s.name}}</option>
          </select>
      
      category:<select v-model="teacherSearchVo.typeId">
               <option value="">--Please select a category--</option>
               <option v-for="(s,index) in categoryList" :key="index" :value="s.id">{{s.name}}</option>
          </select>
      Trade name:<input type="text" v-model="teacherSearchVo.teacherName">
    
      commodity price:<input type="text" v-model="teacherSearchVo.minSalary">-
           <input type="text" v-model="teacherSearchVo.maxSalary">
<br>
 
 <table border="1">
          <tr>
              <th><input type="checkbox" v-model="selectAll" @change="change()">Select all</th>
              <th>commodity ID</th>
              <th>Trade name</th>
              <th>Commodity brand</th>
              <th>Commodity category</th>
              <th>commodity price</th>
              <th>Commodity inventory</th>
              <th>Release time</th>
              <th>Product introduction</th>
              <th>operation</th>
          </tr>
          <tr v-for="(tea,index) in teaList" :key="index">
              <td><input type="checkbox" v-model="dels" :value="tea.id"></td>
              <td>{{tea.id}}</td>
              <td>{{tea.name}}</td>
              <td>{{tea.school.name}}</td>
              <td>
                {{tea.type.name}}
              </td>
              <td>{{tea.price}}</td>
              <td>{{tea.store_num}}</td>
              <td>{{tea.create_time}}</td>
              <td>{{tea.introduction}}</td>
              <td><router-link :to="'/updateTeacher/'+tea.id">modify</router-link>   
                  <a href="#"@ Click =" deletebyid (tea. ID) "> delete</a> 
              </td>
          </tr>
      </table>

js

export default {
    data() {
        return {
            id:[],
            teacherSearchVo:{
                page:1,
                rows:3,
                schoolId:"",
                typeId:""
            },
            teaList:[],//Product list
            schoolList:[],//All schools gather
            categoryList:[],//All category collections
            total:0,//Total number
            dels:[],//id collection for bulk deletion
            selectAll:false,//true select all false select none
        }
    },
    methods: {
        async initTeaList(){
            let res = await this.$http.get("/teacher/condition",{params:this.teacherSearchVo})
            console.log(res)
            this.teaList = res.data.data
            this.total = res.data.total
        }, 
        async initSchoolList(){
            let res = await this.$http.get("/school/all")
            this.schoolList = res.data.data
            
        },
        async initCategoryList(){
            let res = await this.$http.get("/type/all")
            this.categoryList = res.data.data
            console.log(this.categoryList)
            
        },
        handleSizeChange(val) {
            console.log(`each page ${val} strip`);
            this.teacherSearchVo.rows = val
            this.initTeaList()

        },
        handleCurrentChange(val) {
            console.log(`Current page: ${val}`);
            this.teacherSearchVo.page = val
            this.initTeaList()
        },
        async deleteById(id){
            console.log(id)
            let res = await this.$http.delete("/teacher/"+id)
            if(res.data.code==10000){
                alert("Delete succeeded")
                this.initTeaList()
            }else{
                alert("Deletion failed")
            }
        },
        async batchDelete(){
            // Assembly id
            let delIds = "";
            for(let i=0;i<this.dels.length;i++){
                delIds += this.dels[i] + ","
            }
            delIds = delIds.substring(0,delIds.length-1)
            // Call ajax
            let res = await this.$http.delete("/teacher/batchDelete/"+delIds)
            alert("Delete succeeded")
            this.initTeaList()
        },
        change(){
            console.log(this.selectAll)
            if(this.selectAll==true){
                //Select all
                for(let i=0;i<this.teaList.length;i++){
                    this.dels.push(this.teaList[i].id)
                }

            }else{
                this.dels = []
            }
        }
    },
    created() {
        this.initTeaList()
        this.initSchoolList()
        this.initCategoryList()
    },
    watch:{
        'dels':function(){
            if(this.dels.length==this.teaList.length){
                this.selectAll = true
            }else{
                this.selectAll = false
            }
        },
        'teaList':function(){

        }
    }
}

Add function

<router-link to="/addTeacher">New products</router-link>  

Click the Add button to jump to the added page

<template>
  <div>
      <h1>New products</h1>
      Commodity name:<input type="text" v-model="teacher.name"><br>  
      Commodity brand:<select v-model="teacherSearchVo.schoolId">
               <option value="">--Please select a brand--</option>
               <option v-for="(s,index) in schoolList" :key="index" :value="s.id">{{s.name}}</option>
          </select>
            <br>  
      Commodity category:<select v-model="teacherSearchVo.typeId">
               <option value="">--Please select a category--</option>
               <option v-for="(s,index) in typeList" :key="index" :value="s.id">{{s.name}}</option>
          </select>
            <br>
      Product introduction: <input type="text" v-model="teacher.introduction"><br>
      commodity price: <input type="text" v-model="teacher.price"><br>
      Commodity inventory: <input type="text" v-model="teacher.store_num"><br>
      Release time:<input type="date" v-model="teacher.create_time"><br>     
      <input type="button" value="newly added" @click="add()">
  
  
  
  </div>
</template>

<script>
export default {
    data() {
        return {
          teacherSearchVo:{
                page:1,
                rows:3,
                schoolId:"",
                typeId:""
            },
            teacher:{
                sex:"",
                typeId:"",//Default: - please select--
            },//A commodity is an object
            typeList:[],//Item type array
            schoolList:[],//All schools gather
        }
    },
    methods: {
       
        async add(){
            let res = await this.$http.post("/teacher",this.teacher)
            console.log(res)
            if(res.data.code==10000){
                alert("Successfully added")
                this.$router.push("/teacherList")
            }else{
                alert("Failed to add");
            }
        },
        //Method for initializing item type
        async initTypeList(){
            let res = await this.$http.get("/type/all")
            this.typeList = res.data.data
        },
         async initSchoolList(){
            let res = await this.$http.get("/school/all")
            this.schoolList = res.data.data
            
        },
    },
    created() {
        this.initTypeList()
        this.initSchoolList()
    },
}
</script>

<style>

</style>

Modify function

<router-link :to="'/updateTeacher/'+tea.id">modify</router-link> 

Similar to adding a page, you only need to modify js

export default {
    data() {
        return {
            teacherSearchVo:{
                page:1,
                rows:3,
                schoolId:"",
                typeId:""
            },
            teacher:{
                sex:"",
                typeId:"",//Default: - please select--
            },//A commodity is an object
            typeList:[],//Item type array
            schoolList:[],//All schools gather
        }
    },
    methods: {
        async initTeacher(){
            let res = await this.$http.get("/teacher/"+this.id)
            // debugger
            this.teacher = res.data.data
        },
         //Method for initializing item type
        async initTypeList(){
            let res = await this.$http.get("/type/all")
            this.typeList = res.data.data
        },
        async update(){
            let res = await this.$http.put("/teacher",this.teacher)
            if(res.data.code==10000){
                alert("Modified successfully")
                this.$router.push("/teacherList")
            }else{
                alert("Modification failed")
            }
        },
         async initSchoolList(){
            let res = await this.$http.get("/school/all")
            this.schoolList = res.data.data
            
        },
    },  
    created() {
        this.id = this.$route.params.id
        this.initTeacher()
        this.initTypeList()
        this.initSchoolList()
    },
}

Delete function

<a href="#"@ Click =" deletebyid (tea. ID) "> delete</a> 
 async deleteById(id){
            console.log(id)
            let res = await this.$http.delete("/teacher/"+id)
            if(res.data.code==10000){
                alert("Delete succeeded")
                this.initTeaList()
            }else{
                alert("Deletion failed")
            }
        },

At present, the function is basically realized! Let's improve it again

Batch delete

Functional analysis:

In fact, there are many ways to realize batch deletion. Here, I put the id passed in batch into the array, and then the back-end uses the for loop to traverse the deletion.

<input type="checkbox" v-model="dels" :value="tea.id">

js

async batchDelete(){
            // Assembly id
            let delIds = "";
            for(let i=0;i<this.dels.length;i++){
                delIds += this.dels[i] + ","
            }
            delIds = delIds.substring(0,delIds.length-1)
            // Call ajax
            let res = await this.$http.delete("/teacher/batchDelete/"+delIds)
            alert("Delete succeeded")
            this.initTeaList()
        },
        change(){
            console.log(this.selectAll)
            if(this.selectAll==true){
                //Select all
                for(let i=0;i<this.teaList.length;i++){
                    this.dels.push(this.teaList[i].id)
                }

            }else{
                this.dels = []
            }
        },
        watch:{
        'dels':function(){
            if(this.dels.length==this.teaList.length){
                this.selectAll = true
            }else{
                this.selectAll = false
            }
        },
        'teaList':function(){

        }
    }

Fuzzy query multi condition query

Think about how to write it. The code has been posted on it

Elementui implements paging query

After installing the ui plug-in using npm, change the official website template

<el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="teacherSearchVo.page"
        :page-sizes="[1,2,3,4,50,1000]"
        :page-size="teacherSearchVo.rows"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

Parameter interpretation:

@ size change: the number of entries per page is changed through the drop-down list box

@ current change: the current page number has changed

Current page: current page 2

Page sizes: drop-down list box to set the number of pieces displayed on each page

Page size: the number of items displayed on each page is 3

Total: the total number of data in the database 16. Function: calculate the total number of pages

js

        handleSizeChange(val) {
            console.log(`each page ${val} strip`);
            this.teacherSearchVo.rows = val
            this.initTeaList()

        },
        handleCurrentChange(val) {
            console.log(`Current page: ${val}`);
            this.teacherSearchVo.page = val
            this.initTeaList()
        },

Postscript

📢 Blog home page: manor's blog_ Little manor_CSDN blog - Java, full stack, big data Blogger
📢 Welcome to praise 👍 Collection ⭐ Leaving a message. 📝 Please correct any errors!
}
},
'teaList':function(){

    }
}


## Fuzzy query multi condition query

Think about how to write it,The code has been posted above



## Elementui implements paging query

use npm Installation completed ui After plug-in,Change the official website template

<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="teacherSearchVo.page"
:page-sizes="[1,2,3,4,50,1000]"
:page-size="teacherSearchVo.rows"
layout="total, sizes, prev, pager, next, jumper"
:total="total">

Parameter interpretation:

​	@size-change: The number of entries per page is changed through the drop-down list box

​    @current-change: The current page number has changed

​    current-page:What page is it currently? 2

​    page-sizes: Drop down list box to set the number of items displayed on each page

​    page-size: Number of items displayed per page 3

​    total: The total number of entries of this data in the database is 16. Its function is to calculate the total number of pages



js

    handleSizeChange(val) {
        console.log(`each page ${val} strip`);
        this.teacherSearchVo.rows = val
        this.initTeaList()

    },
    handleCurrentChange(val) {
        console.log(`Current page: ${val}`);
        this.teacherSearchVo.page = val
        this.initTeaList()
    },


# Postscript

📢Blog home page:[manor Blog_Little manor_CSDN Blog-Java,Full stack,Big data Blogger](https://blog.csdn.net/qq_58432443)
📢Welcome to praise 👍 Collection ⭐Leaving a message. 📝 Please correct any errors!
📢This paper consists of manor Original, launched in CSDN Blog🙉

Topics: Java Front-end Spring Boot Vue.js