Vue+Mysql+SpringBoot simple addition, deletion, modification and check

About Spring

Summary of basic knowledge about mybatis+maven

Detailed configuration of spring+springmvc+mybatis integration in maven

SpringBoot+Mybatis+Redis basic configuration

A make-up homework written in the past two days, or write it down. Otherwise, if you didn't type the code after a month, you would forget it, and talk nonsense, you need to get the project source code yourself.

Link: https://pan.baidu.com/s/1RQ1rD9fARI37bhCHwLLVOg 
Extraction code: gio8 
first post the effect picture, the GIF picture is not too lazy to get the software. Try it yourself.

First of all, you need to have a certain foundation of vue and springboot. For springboot, please read my blog first. It may not be detailed, but I mentioned the problem.

https://blog.csdn.net/qq_41520636/article/details/87192263

Old rules, let's talk about the trouble this thing has encountered first.

Question one:

When using vue and axios, the background post request is connected, and the background always receives null values. After Baidu was almost unable to do so, he chose to give up treatment. If you change the GET request method, there are big guys who can solve it, please send a private message or comment to inform. Thank you!

--------------20200417 update ----------------------------

This problem has been solved!

Solution link: https://blog.csdn.net/qq_41520636/article/details/104726763

Question two:

In fact, it’s just that I forgot how to use vue. I want the value of the checkbox selected, and the corresponding value of the v-model I wrote in the data is

checkData:''

This is a wrong way of writing, otherwise you will click a check box and all other check boxes will be selected.

The correct approach is

checkData:[]

Question three:

I use the automatic code generator assistance, so Baidu has a lot of things. Is it so troublesome to install the Shenma plug-in? The configuration in pom.xml is also.

This is not a problem, it's just that I was misled.

How good is it to write java directly, simple and convenient.

Question four:

When I designed the database, it was based on the one-to-many relationship of interest. Because the previous code was forgotten, I got stuck in my head and couldn't do it.

From the table of students I want in the controller, through List<Hobbys> directly in

@ResponseBody
@RequestMapping(value ="/addStudent")
public ResponseCode addStudent(@Valid Student student){
    System.out.println(student.toString());
    int insert = studentService.insert(student);
    return new ResponseCode(insert);
}
public class Student implements Serializable {
   
   
private List<Hobbys> hobby;

This list passes directly

hobby.id was directly added to the data, but it failed. The obtained value has always been a null value, and then I can only add a hobby parameter to get it.

Question five:

Regarding the cross-domain request, I configured it to solve the problem.

The above is almost the problem I encountered. Below is the code post.

Post code automatically generated

package org.lanqiao.test;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TestGenerator
 * @Description TODO
 * @Author lisonglin
 * @Date 2018/12/5 17:00
 * @Version 1.0
 */
public class TestGenerator {

    /***
     * 功能描述:
     *  调用generatorConfig.xml
     * @param: []
     * @return: void
     * @auther: 李松林
     * @date: 2018/12/8 19:50
     */
    public void generator(){
        List<String> warnings=new ArrayList<String>();
        //更新数据库时,请修改项目的xml配置绝对路径
        File file=new File("E:\\MyJAVA\\SpringMakeup\\src\\main\\conf\\generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = null;
        try {
            config = cp.parseConfiguration(file);
            DefaultShellCallback shellCallback = new DefaultShellCallback(true);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
            myBatisGenerator.generate(null);
            System.out.println(warnings);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        try {
            TestGenerator generatorSqlmap = new TestGenerator();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>

    <context id="testTables" targetRuntime="MyBatis3" defaultModelType="flat">

        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <property name="javaFileEncoding" value="UTF-8"/>

        <!-- 生成注释配置 -->
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
            <property name="javaFileEncoding" value="UTF8"/>
            <!--生成的注释包含时间戳(避免重复提交SVN,设为true)-->
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <!--
        <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
            connectionURL="jdbc:oracle:thin:@150.16.17.22:1521/wsbs" userId="hr"
            password="hr123">
        </jdbcConnection>-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/sys?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
                        userId="root"
                        password="123">
        </jdbcConnection>

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="org.lanqiao.model"
                            targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- targetProject:mapper.xml映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="org.lanqiao.mapper"
                         targetProject="E:/MyJAVA/SpringMakeup/src/main/conf">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- targetPackage:mapper.java接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="org.lanqiao.mapper"
                             targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>


        <!-- 指定数据库表 -->
        <!--  enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
        enableSelectByExample="false" selectByExampleQueryId="false"-->
        <!--不生成example-->
        <!--<table tableName="items"></table> -->
        <table tableName="hobbys" mapperName="HobbysMapper" domainObjectName="Hobbys"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
            <!--下划线转驼峰命名-->
            <property name="useActualColumnNames" value="false"/>
            <!--指定自动生成主键的属性-->
            <generatedKey column="id" sqlStatement="MySql" identity="true"></generatedKey>
            <!--元素从将某些属性默认计算的值更改为指定的值。-->
            <!--<columnOverride  column="message_content" javaType="List&lt;Teacher&gt;"></columnOverride >-->
            <!--忽略字段-->
            <!--<ignoreColumn column="file_id"></ignoreColumn>-->
            <!--<ignoreColumn column="lyric_id"></ignoreColumn>-->
        </table>


    </context>
</generatorConfiguration>

Project package diagram


#热部署
#开启
spring.devtools.restart.enabled=true 
#监听目录
spring.devtools.restart.additional-paths=src/main/java 

#mybatis
#mybatis-config.xml配置文件的路径
#mybatis.configLocation=classpath:mybatis-config.xml
#SQL语句映射文件
#mybatis.mapper-locaitons= classpath*:com/example/mapper/*.xml
mybatis.mapper-locations=classpath*:org/lanqiao/mapper/*.xml
# 类的别名的包
mybatis.type-aliases-package=org.lanqiao.model
#驼峰命名法
mybatis.configuration.mapUnderscoreToCamelCase=true
#允许返回多个结果集
mybatis.configuration.multipleResultSetsEnabled=true
#使用jdbc的getGeneratedKeys获取数据库自增主键值
mybatis.configuration.useGeneratedKeys=true
#日志
#mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#延迟加载总开关( 查询时,关闭关联对象即时加载以提高性能)
mybatis.configuration.lazyLoadingEnabled=false
#侵入懒加载,设置为false则按需加载,否则会全部加载
mybatis.configuration.aggressiveLazyLoading=false

spring.datasource.url=jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.lanqiao</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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.0.0</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- tomcat的支持.-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!--自动生成bean-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <!-- 对象转换成json引入如下依赖 -->
        <!-- 文档:https://www.yiibai.com/jackson/jackson_first_application.html#article-start -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.4</version>
        </dependency>

    </dependencies>

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

</project>

 

package org.lanqiao.controller;

import org.lanqiao.model.Hobbys;
import org.lanqiao.model.ResponseCode;
import org.lanqiao.model.Student;
import org.lanqiao.service.HobbysService;
import org.lanqiao.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;

/**
 * @ClassName MainController
 * @Description TODO
 * @Author lisonglin
 * @Date 2019/3/28 0:03
 * @Version 1.0
 */
@Controller
public class MainController {

    @Autowired
    StudentService studentService;
    @Autowired
    HobbysService hobbysService;

    @ResponseBody
    @RequestMapping("/getAll")
    public List<Student> getStudent(){
        List<Student> students = studentService.getAll();
        System.out.println(students);
        return students;
    }

    @ResponseBody
    @RequestMapping(value ="/addStudent")
    public ResponseCode addStudent(@Valid Student student, String hobbys){
        System.out.println(student.toString());
        System.out.println("兴趣是:"+hobbys);
        int insert = studentService.insert(student,hobbys);
        return new ResponseCode(insert);
    }

    @ResponseBody
    @RequestMapping(value ="/updateStudent")
    public ResponseCode updateStudent(@Valid Student student,String hobbys){
        System.out.println(student+"兴趣:"+hobbys);
        int i = studentService.updateByPrimaryKey(student, hobbys);
        return new ResponseCode(i);
    }

    @ResponseBody
    @RequestMapping(value ="/deleteStudent")
    public ResponseCode deleteStudent(Integer studentId){
        int i = studentService.deleteByPrimaryKey(studentId);
        return new ResponseCode(i);
    }

    @ResponseBody
    @RequestMapping("/getHobbys")
    public List<Hobbys> getHobbys(){
        return hobbysService.getHobbys();
    }

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

}
package org.lanqiao.dao;

import org.lanqiao.mapper.StudentHobbysMapper;
import org.lanqiao.mapper.StudentMapper;
import org.lanqiao.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @ClassName StudentDao
 * @Description TODO
 * @Author lisonglin
 * @Date 2019/3/27 23:51
 * @Version 1.0
 */
@Repository
public class StudentDao {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    StudentHobbysMapper studentHobbysMapper;

    public int deleteByPrimaryKey(Integer id){
        studentMapper.deleteByPrimaryKey(id);
        studentHobbysMapper.deleteHobbyIdToStudent(id);
        return 1;
    };

    public int insertStudent(Student student, String hobbys){
        studentMapper.insert(student);
        String regex = ",";
        String[] arr = hobbys.split(regex);
        for(int i=0;i<arr.length;i++){
            studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
        }
        return 1;
    };

    public int insertSelective(Student record){
        return studentMapper.insertSelective(record);
    };

    public Student selectByPrimaryKey(Integer id){
        return studentMapper.selectByPrimaryKey(id);
    };

    public int updateByPrimaryKeySelective(Student record){
        return studentMapper.updateByPrimaryKeySelective(record);
    };

    public int updateByPrimaryKey(Student student, String hobbys){
        studentMapper.updateByPrimaryKey(student);
        studentHobbysMapper.deleteHobbyIdToStudent(student.getId());
        String regex = ",";
        String[] arr = hobbys.split(regex);
        for(int i=0;i<arr.length;i++){
            studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
        }
        return 1;
    };

    public List<Student> getAll() {
        return studentMapper.getAll();
    }

}
package org.lanqiao.dao;

import org.lanqiao.mapper.HobbysMapper;
import org.lanqiao.model.Hobbys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @ClassName HobbysDao
 * @Description TODO
 * @Author lisonglin
 * @Date 2019/3/30 15:54
 * @Version 1.0
 */
@Repository
public class HobbysDao {

    @Autowired
    HobbysMapper hobbysMapper;

    public List<Hobbys> getHobbys() {
        return hobbysMapper.getHobbys();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.mapper.HobbysMapper">
  <select id="getHobbys" resultType="Hobbys">
    select * from hobbys
  </select>


</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.mapper.StudentHobbysMapper">

    <insert id="insertStudentHobby">
        insert into stu_hobby (id,hobby) values (#{studentId},#{hobbyId})
    </insert>

    <delete id="deleteHobbyIdToStudent">
        delete from stu_hobby where id=#{studentId}
    </delete>

</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.mapper.StudentMapper">
  <resultMap id="BaseResultMap" type="org.lanqiao.model.Student">
    <id column="id"  property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="age"  property="age" />
    <result column="score" jdbcType="DOUBLE" property="score" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, sex, age, score
  </sql>
  <sql id="Base_All">
    select s.id sid,s.`name`,s.sex,s.age,s.score,h.id,h.hobby
    from student s
    join stu_hobby sh
    on s.id=sh.id
    join hobbys h
    on sh.hobby=h.id
  </sql>

  <select id="getAll" resultMap="getStudentAll">
    <include refid="Base_All"></include>
  </select>

  <resultMap id="getStudentAll" type="Student">
    <id column="sid" property="id"></id>
    <result column="name" property="name"></result>
    <result column="sex" property="sex"></result>
    <result column="age" property="age"></result>
    <result column="score" property="score"></result>
    <collection property="hobby" ofType="Hobbys">
      <id column="id" property="id"></id>
      <result column="hobby" property="hobby"></result>
    </collection>
  </resultMap>

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from student
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from student
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="org.lanqiao.model.Student">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into student (name, sex, age,
      score)
    values (#{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
      #{score,jdbcType=DOUBLE})
  </insert>


  <insert id="insertSelective" parameterType="org.lanqiao.model.Student">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        name,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="age != null">
        age,
      </if>
      <if test="score != null">
        score,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
      <if test="score != null">
        #{score,jdbcType=DOUBLE},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="org.lanqiao.model.Student">
    update student
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="score != null">
        score = #{score,jdbcType=DOUBLE},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <update id="updateByPrimaryKey" parameterType="org.lanqiao.model.Student">
    update student
    set name = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      score = #{score,jdbcType=DOUBLE}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
package org.lanqiao.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 解决跨域请求配置
 * @ClassName AccessConfig
 * @Description TODO
 * @Author lisonglin
 * @Date 2019/3/30 22:27
 * @Version 1.0
 */
@Configuration
public class AccessConfig extends WebMvcConfigurationSupport {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }

}
package org.lanqiao.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName MapperScannerConfig
 * @Description TODO
 * @Author lisonglin
 * @Date 2019/3/27 22:43
 * @Version 1.0
 */
@Configuration
public class MapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //指定xml配置文件的路径
        mapperScannerConfigurer.setBasePackage("org.lanqiao.mapper");
        return mapperScannerConfigurer;
    }

}
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>vue增删改查</title>
</head>
<body>
    <div id="app1">
        <table border="1" cellpadding="0" cellspacing="0">
            <tr>
                <td colspan="2" align="center">学生基本信息</td>
            </tr>
            <tr>
                <td>姓名</td>
                <td>
                    <input v-model="name" style="width:150px" />
                </td>
            </tr>
            <tr>
                <td>性别</td>
                <td>
                    <input type="radio" id="boy" value="男" v-model="sex">
                    <label for="boy">男</label>
                    <input type="radio" id="girl" value="女" v-model="sex">
                    <label for="girl">女</label>
                </td>
            </tr>
            <tr>
                <td>年龄</td>
                <td>
                    <select v-model="age">
                        <option v-for="option in options" v-bind:value="option.value"
                                :disabled="option.value==0?true:false" :class="{statusbtn:option.value==0}">
                            {
   
   { option.text }}
                        </option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>成绩</td>
                <td>
                    <input v-model.number="score" placeholder="请输入成绩"  style="width:150px"/>
                </td>
            </tr>
            <tr>
                <td>兴趣</td>
                <td>
                    <span v-for="(studentHobby,index) in studentHobbys" >
                        <input type="checkbox" name="interests" v-bind:value="index+1" v-model="checkData">
                        <label>{
   
   { studentHobby.hobby }}</label>
                    </span>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" :value="form" @click="submission" v-if="isAdd"/>
                    <input type="submit" :value="form" @click="update" v-else="!isAdd"/>
                    <input type="submit" id="reset" value="重置" v-on:click="resets"/>
                </td>
            </tr>
        </table>


        <br /><br /><br /><br />
        <table border="1" cellspacing="0" cellpadding="0" id="listTable">
        <tr>
            <td>选中</td>
            <td>姓名</td>
            <td>性别</td>
            <td>年龄</td>
            <td>成绩</td>
            <td>兴趣</td>
            <td>操作</td>
        </tr>
        <tr>
            <td>
                <label>全选</label>
                <input type="checkbox" name="item" v-model='checked' v-on:click='checkedAll'/>
            </td>
            <td  colspan="6" align="center">
                <input type="button" value="选中删除" @click="delRow"/>
            </td>
        </tr>
        <tr v-for="(items,index) in student">
            <td><input type="checkbox" name="item" v-model="checkList" :value="items.id"/>{
   
   {1 + index}}</td>
            <td>{
   
   {items.name}}</td>
            <td>{
   
   {items.sex}}</td>
            <td>{
   
   {items.age}}</td>
            <td>{
   
   { items.score }}</td>
            <td><span v-for="item in items.hobby">{
   
   {item.hobby}} </span></td>
            <td>
                <input type="button" value="删除" @click="del(items.id)"/>
                <input type="button" name="update" value="修改" @click="modify(items)" />
            </td>
        </tr>
        </table>
    </div>
    <style>
        .statusbtn {
            color: #d6caca;
            cursor: not-allowed; /*这个在button上面才管用,是一个禁用的小标识*/
        }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/qs/6.6.0/qs.min.js"></script>

    <script>
        var app1=new Vue({
            el:'#app1',
            data:{
                options: [
                    { text: '请选择', value: '0' },
                    { text: '16', value: '16' },
                    { text: '17', value: '17' },
                    { text: '18', value: '18' },
                    { text: '19', value: '19' },
                    { text: '20', value: '20' },
                    { text: '21', value: '21' },
                    { text: '22', value: '22' },
                    { text: '23', value: '23' },
                ],
                id:'',
                name:'',
                age:'0',
                sex:'男',
                score:'',
                studentHobbys:[],
                student:[],
                form:'提交',
                isAdd: true,
                checkData: [],//后台请求的数据
                checked:false,//全选框
                checkList: []
            },
            watch: { // 监视双向绑定的数据数组
                'checkList': {
                    handler(val, oldVal){ // 数据数组有变化将触发此函数
                        if (val.length === this.student.length) {
                            this.checked = true;
                        } else {
                            this.checked = false;
                        }
                    },
                    deep: true // 深度监视
                }
            },
            created: function (){
                this.getStudent();
                this.getHobbysAll();
            },
            methods: {
                getHobbysAll: function(){
                    axios.get('http://localhost:8080/getHobbys')
                        .then(function (response) {
                            var arr = response.data;
                            app1.studentHobbys = arr;
                        })
                        .catch(function (error) {

                        })
                },
                getStudent:function () {
                    axios.post('http://localhost:8080/getAll').
                    then(function (response){
                        var arr=response.data;
                        app1.student=arr;
                    }) .catch(function (error) {

                    })
                },
                submission:function () {
                    // console.log("选中:"+this.checkData);
                    //获取兴趣
                    var selectedValue=this.checkData;
                    axios.get('http://localhost:8080/addStudent?name='+this.name+'&sex='+this.sex+'&age='+
                       this.age+'&score='+this.score+'&hobbys='+selectedValue)
                        .then(function (response) {
                            //更新
                            app1.getStudent();
                            //重置
                            app1.resets();
                        }).catch(function (error) {

                        })
                },
                del:function (e) {
                    // console.log(e);
                    axios.get('http://localhost:8080/deleteStudent?studentId='+e)
                        .then(function (response) {
                            app1.getStudent();
                        }).catch(function (error) {

                    })
                },
                //选中删除
                delRow:function(){
                    for(var i=0;i<this.checkList.length;i++){
                        axios.get('http://localhost:8080/deleteStudent?studentId='+this.checkList[i])
                            .then(function (response) {
                                app1.getStudent();
                            }).catch(function (error) {

                        })
                    }
                },
                //修改回显
                modify:function (items) {
                    //重置
                    app1.resets();
                    //更新按钮
                    app1.form='更新';
                    //回显
                    this.id=items.id;
                    this.name=items.name;
                    this.sex=items.sex;
                    this.age=items.age;
                    this.score=items.score;
                    var arr=[];
                    for(var i=0;i<items.hobby.length;i++){
                        arr.push(items.hobby[i].id);
                    }
                    this.checkData=arr;
                    this.isAdd=false;
                },
                update:function(items){
                    axios.get('http://localhost:8080/updateStudent?id='+this.id+'&name='+this.name+'&sex='+this.sex+'&age='+
                        this.age+'&score='+this.score+'&hobbys='+this.checkData)
                        .then(function (response) {
                            app1.getStudent();
                            app1.resets();
                        }).catch(function (error) {

                    })
                },
                resets:function () {
                    this.name='',
                    this.sex='男',
                    this.age='0',
                    this.score=''
                    this.checkData=[],
                    this.form='提交',
                    this.isAdd=true
                },
                checkedAll: function(){
                    //全选和反选
                    var _this = this;
			// .log(_this.checked+"---"+_this.checkList+"----"+_this.student)
                    this.$nextTick(function() {
                        if(!_this.checked){
                            _this.checkList = _this.student.map(function(json,index){
                                // console.log(json.id+","+index)
                                return json.id;
                            })
                        }else {
                            _this.checkList = []
                        }
                    });
                },
            }
        });
    </script>
</body>
</html>

The above basic and important codes are posted, see the source code in detail.

Guess you like

Origin blog.csdn.net/qq_41520636/article/details/88929298