SpringBoot +Vue + elementUI+axios 简单增删查改功能解析

不点 阅读:219 2021-03-31 13:45:25 评论:0

1、效果整体展示:

 

2、SpringBoot项目部分(使用模拟数据)

实体对象

package com.zzg.domain; 
 
import java.io.Serializable; 
 
import lombok.AllArgsConstructor; 
import lombok.Data; 
import lombok.NoArgsConstructor; 
import lombok.experimental.Accessors; 
 
@SuppressWarnings("serial") 
@Data // 自动生成get、set、toString、equals方法 
@AllArgsConstructor // 全参构造方法 
@NoArgsConstructor // 无参构造方法 
@Accessors(chain = true) // 链式编程 
public class User implements Serializable { 
	private String id; 
	private String name; 
	private Integer age;  
 
} 

控制层

package com.zzg.controller; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import org.apache.commons.lang3.RandomUtils; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.CrossOrigin; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import com.alibaba.druid.util.StringUtils; 
import com.alibaba.fastjson.JSONObject; 
import com.zzg.common.model.Result; 
import com.zzg.domain.User; 
import io.swagger.annotations.Api; 
import io.swagger.annotations.ApiOperation; 
import io.swagger.annotations.ApiParam; 
 
@Controller 
@RequestMapping("/api/test") 
@CrossOrigin 
@Api(value = "模拟测试Controlle", tags = "模拟测试操作服务") 
public class TestController { 
	 
	static List<User> container = new ArrayList<User>(); 
	static { 
		container.add(new User("1","周晨曦",2)); 
		container.add(new User("2","张三",2)); 
		container.add(new User("3","李四",2)); 
		container.add(new User("4","王五",2)); 
		container.add(new User("5","李六",2)); 
		 
	} 
	 
	@ApiOperation(httpMethod = "POST", value = "模拟测试对象保存") 
	@RequestMapping(value = "/insert", method = { RequestMethod.POST}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public Result insert( 
			@RequestBody @ApiParam(name = "模拟测试对象", value = "json格式对象", required = true)JSONObject entity) { 
		User user = entity.toJavaObject(User.class); 
		if(StringUtils.isEmpty(user.getId())) { 
			RandomUtils.nextInt(6, 1000); 
			Integer sid = RandomUtils.nextInt(); 
			user.setId(String.valueOf(sid)); 
		} 
		 
		container.add(user); 
		return Result.ok(); 
	} 
	 
	@ApiOperation(httpMethod = "POST", value = "模拟测试对象删除") 
	@RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE }) 
	@ResponseBody 
	public Result delete( 
			@PathVariable String id) { 
 
//		container.stream() 
//		.filter(u-> u.getId().equalsIgnoreCase(id)) 
//		.findFirst() 
//		.ifPresent(u->System.out.println(u.getName())); 
		container.removeIf(u -> u.getId().equalsIgnoreCase(id)); 
		 
		return Result.ok(); 
		 
	} 
	 
	@ApiOperation(httpMethod = "POST", value = "模拟测试对象更新") 
	@RequestMapping(value = "/update", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	public Result update( 
			@RequestBody @ApiParam(name = "用户对象", value = "json格式对象", required = true)  User entity) { 
		container.removeIf(u -> u.getId().equalsIgnoreCase(entity.getId())); 
		container.add(entity); 
		return Result.ok(); 
	} 
	 
	@RequestMapping(value="/find", method={RequestMethod.GET}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	@ApiOperation(httpMethod = "GET", value = "模拟测试对象查询") 
	public String find() { 
		JSONObject obj = new JSONObject(); 
		 
		obj.put("code", 0); 
		obj.put("data", container); 
		return obj.toJSONString(); 
	} 
} 

3、VUE 项目部分

第一步:新建Vue 项目(my_one)

#创建一个基于webpack模板的新项目 
vue init webpack D:\node_workspace\my_one 
# 切换至项目路径 
cd d:D:\node_workspace\my_one 
# 安装项目依赖文件 
cnpm install 
# 项目启动 
cnpm run dev 

第二步:安装element-ui 

# 切换至项目路径 
cd d:D:\node_workspace\my_one 
# 安装element-ui 
cnpm i element-ui -S

编辑Vue项目(my_one)的main.js ,添加如下代码片段:

import ElementUI from 'element-ui'; 
import 'element-ui/lib/theme-chalk/index.css'; 
 
Vue.use(ElementUI);

第三步:安装axios

# 切换至项目路径 
cd d:D:\node_workspace\my_one 
# 安装axios 
cnpm i axios -S

编辑Vue项目(my_one)的main.js ,添加如下代码片段:

import axios from '../node_modules/axios' 
# 设置后端请求地址 
axios.defaults.baseURL='http://localhost:9097/api' 
 
Vue.prototype.$axios = axios

第四步:编辑src/components/HelloWorld.vue组件:

<template> 
  <div> 
 <p style="text-align: left;"> 
    <el-button type="primary" @click="dialogFormAdd = true">添加</el-button> 
    </p> 
 
    <el-table :data="tableData" stripe border style="width:100%" highlight-current-row> 
      <el-table-column type="selection" width="55"> 
      </el-table-column> 
      <el-table-column prop="id" label="ID" align="center" min-width="120"> 
        <template slot-scope="scope"> 
          <span>{
  { scope.row.id}}</span> 
        </template> 
      </el-table-column> 
      <el-table-column prop="age" label="年龄" align="center" min-width="100"> 
        <template slot-scope="scope"> 
          <span>{
  { scope.row.age}}</span> 
        </template> 
      </el-table-column> 
      <el-table-column prop="name" label="姓名" align="center" min-width="120"> 
        <template slot-scope="scope"> 
          <span>{
  { scope.row.name}}</span> 
        </template> 
      </el-table-column> 
      <el-table-column label="操作" align="center" min-width="100"> 
        <template slot-scope="scope"> 
          <el-button type="info" @click="toEdit(scope)">修改</el-button> 
          <el-button type="info" @click="deleteUser(scope)">删除</el-button> 
        </template> 
      </el-table-column> 
    </el-table> 
 
    <el-dialog title="修改人员" :visible.sync="dialogFormEdit"> 
      <el-form :model="person"> 
        <el-form-item label="编号" > 
          <el-input v-model="person.id" auto-complete="off"></el-input> 
        </el-form-item> 
        <el-form-item label="年龄" > 
          <el-input v-model="person.age" auto-complete="off"></el-input> 
        </el-form-item> 
        <el-form-item label="姓名" > 
          <el-input v-model="person.name" auto-complete="off"></el-input> 
        </el-form-item> 
      </el-form> 
      <div slot="footer" class="dialog-footer"> 
        <el-button @click="dialogFormEdit = false">取 消</el-button> 
        <el-button type="primary" @click="edit(person)">确 定</el-button> 
      </div> 
    </el-dialog> 
 
    <el-dialog title="添加人员" :visible.sync="dialogFormAdd"> 
      <el-form :model="person"> 
        <el-form-item label="编号" > 
          <el-input v-model="person.id" auto-complete="off"></el-input> 
        </el-form-item> 
        <el-form-item label="年龄" > 
          <el-input v-model="person.age" auto-complete="off"></el-input> 
        </el-form-item> 
        <el-form-item label="姓名" > 
          <el-input v-model="person.name" auto-complete="off"></el-input> 
        </el-form-item> 
      </el-form> 
      <div slot="footer" class="dialog-footer"> 
        <el-button @click="dialogFormAdd = false">取 消</el-button> 
        <el-button type="primary" @click="add(person)">确 定</el-button> 
      </div> 
    </el-dialog> 
  </div> 
</template> 
 
<script> 
export default { 
  name: 'HelloWorld', 
  data () { 
     return { 
        tableData: [], 
        dialogFormEdit: false, 
        dialogFormAdd:false, 
        person: { 
          id: '', 
          age: '', 
          name: '' 
        } 
      } 
  }, 
   methods: { 
      init () { 
        var self = this 
        this.$axios.get('/test/find') 
          .then(function (res) { 
            self.tableData = res.data.data 
          }) 
          .catch(function (err) { 
            console.log(err) 
          }) 
      }, 
      add (person) { 
        this.$axios({ 
            method:'post', 
            url:'/test/insert', 
            data:{'name': person.name, 'age':person.age}, 
            headers:{ 
                'Content-Type':'application/json;charset=utf-8'      //改这里就好了 
          } 
        }).then(res => { 
          this.$message.success('添加成功') 
          this.dialogFormAdd = false 
          this.init() 
        }) 
          .catch(function (error) { 
            console.log(error) 
          }) 
      }, 
      edit (person) { 
        var params ={ 
          'id' : person.id, 
          'name' : person.name, 
          'age' :  person.age 
        } 
 
        this.$axios({ 
          method:'post', 
          url:'/test/update', 
          data:params, 
          headers:{ 
                'Content-Type':'application/json;charset=utf-8'      //改这里就好了 
          } 
        }).then(res => { 
          this.$message.success('修改成功') 
          this.dialogFormEdit = false 
          this.init() 
        }).catch(function (error) { 
            console.log(error) 
        }) 
      }, 
      toEdit (scope) { 
        this.person.id = scope.row.id 
        this.person.age = scope.row.age 
        this.person.name = scope.row.name 
        this.dialogFormEdit = true 
      }, 
      deleteUser (scope) { 
        if (!scope.row.id) { 
          this.tableData.splice(scope.$index, 1) 
        } else { 
          this.$confirm('确认是否删除', '提示', { 
            confirmButtonText: '确定', 
            cancelButtonText: '取消', 
            type: 'warning', 
            center: true 
          }) 
            .then(() => { 
              console.log(scope.row.id) 
              this.$axios.delete('/test/delete/' + scope.row.id, {id: scope.row.id}).then(res => { 
                this.$message.success('删除成功') 
                this.init() 
              }) 
                .catch(function (error) { 
                  console.log(error) 
                }) 
            }) 
            .catch(() => { 
              this.$message({ 
                type: 'info', 
                message: '已取消删除' 
              }) 
            }) 
        } 
      } 
    }, 
    mounted: function () { 
      this.init() 
    } 
} 
</script> 
 
<!-- Add "scoped" attribute to limit CSS to this component only --> 
<style scoped> 
h1, h2 { 
  font-weight: normal; 
} 
ul { 
  list-style-type: none; 
  padding: 0; 
} 
li { 
  display: inline-block; 
  margin: 0 10px; 
} 
a { 
  color: #42b983; 
} 
</style> 

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
排行榜
KIKK导航

KIKK导航

关注我们