Vue+Mysql+SpringBoot简单增删改查

关于Spring篇

关于mybatis+maven基本知识掌握总结

maven中spring+springmvc+mybatis整合详细配置

SpringBoot+Mybatis+Redis基础配置

这两天写的一个补考作业,敲完还是记录下。不然一个月后没敲代码又忘记了,废话多说,需要项目源码自己拿。

链接:https://pan.baidu.com/s/1RQ1rD9fARI37bhCHwLLVOg 
提取码:gio8 
先贴张效果图,GIF图没下软件懒得弄了。自己试验。

首先需要你有一定的vue和springboot基础,springboot可以先看看我这篇博客,可能没讲的细,但是问题点我是提到了。

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

老规矩,先说说这个东西遇到的麻烦。

问题一:

在使用vue和axios时,对接后台的post请求,后台一直接收null值。几近百度没法后,选择放弃治疗。换了GET请求方式,有大佬可以解决,麻烦再私信或评论告知。谢谢!

--------------20200417更新----------------------------

此问题已解决!

解决方案链接:https://blog.csdn.net/qq_41520636/article/details/104726763

问题二:

其实只是我忘记vue怎么使用的问题,我想要复选框选中的值,而我在data中写的v-model对应值是

checkData:''

这是错误的写法,不然会点击一个复选框,其他复选框全部选上。

正确的做法是

checkData:[]

问题三:

我使用的是自动生成代码generator辅助,所以百度了很多东西,要安装神马插件,有这么麻烦吗?pom.xml里的配置也是。

这个不算问题吧,只是我被误导了而已。

直接写java运行多好,简单方便易捷。

问题四:

就是我设计数据库时,是按照兴趣一对多的关系来的,因为以前的代码忘干净了,所以一时脑袋卡壳,做不出来。

从controller中我想要的学生表,通过List<Hobbys>直接在

@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;

这个list直接通过

hobby.id直接添加进数据,可惜失败了。获取到的值一直是null值,退而次之,我只能单独添加一个hobby参数来获取。

问题五:

关于请求跨域问题,我配置了下,才解决问题。

以上差不多就是我遇到的问题了,下面是代码贴。

先贴代码自动生成

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>

项目包图


#热部署
#开启
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>

以上基本重要代码都贴出来,详细看源码。

猜你喜欢

转载自blog.csdn.net/qq_41520636/article/details/88929298