首页技术栈归档照片墙音乐日记随想收藏夹友链留言关于

vue+elementUI实现简单的CURD(2.x)

写作时间:2026-07-08

vue+elementUI实现简单的CURD(2.x)

解决跨区问题

在后台config进行配置

package com.ketai.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
*解决跨域问题
*/
@Configuration
public class webConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")//允许所有路径访问
                .allowedOrigins("*")//允许所有原始请求
                .allowedHeaders("*")//允许所有请求头
                .allowedMethods("GET","POST","DELETE","HEAD","PUT","OPTIONS")//请求路径的方式
                .maxAge(3600);//设置过期时间
    }
}

安装axios和elementUI和路由

#安装axios
npm install --save axios vue-axios
#安装elementUI
npm i element-ui -S
#安装路由
#npm install vue-router@3
npm install vue-router@3 or 4

引用axios和elementUI和路由

在mian.js中引用axios和elementUI和路由

import Vue from 'vue'
import App from './App'
#router下的index.js
#引入路由    
import router from "./router/index"
Vue.config.productionTip = false
#导入element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from "axios";
//注册axios为全局的变量
Vue.prototype.$axios=axios;
//注册ElementUI
Vue.use(ElementUI);

new Vue({
  el: '#app',
  #导入路由  
  router,
  components: { App },
  template: '<App/>'
})

在router目录下新建一个index.js

import Vue from "vue"
#导入路由    
import Router from "vue-router";
Vue.use(Router);
//建立路由关系,export将路由器对象暴露给外界
//path:路由地址
//component:路由的组件
//@表示src
//配置路由
const router=new Router({

  routes:[
    { 
      name:"list",//用于展示数据
      path:'/',
      component: ()=>import("@/components/news/List")
     },

      {
      path:'/detail/:id', //路由传参,参数名id,跳转至详情页面
      component: ()=>import("@/components/news/Details")
    }
      ]
});
export default router;

实现CURD和分页详情操作

在components下新建一个index.Vue用于展示数据

<template>
  <div>
    <!--展示组件-->
    <router-view></router-view>
  </div>
</template>

<script>
    export default {
        name: "index"
    }
</script>

<style scoped>

</style>

在App.Vue下配置

<template>
  <div id="app">
<index></index>
  </div>
</template>
<script>
<!--导入index-->    
import index from "./components/index";
export default {
  name: 'App',
  components: {
    index,
  }
}
</script>

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

在components下新建一个news包下新建一个List组件

<template>
  <div>
    <h2>新闻列表</h2>
    <el-row class="newssavebtn">
      <el-button type="primary" @click="newsAdd()" icon="el-icon-plus" >新增</el-button>
    </el-row>
    <el-table
      :data="newsList"
      style="width: 100%">
      <el-table-column
        prop="title"
        label="标题"
        width="180">
      </el-table-column>
      <el-table-column
        prop="publisher"
        label="发布人">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="发布时间">
      </el-table-column>
      <el-table-column label="操作">
          <!--template slot-scope="scope":存的是后台的数据-->
        <template slot-scope="scope">
         <!--跳转至详情页面-->
          <router-link :to="{path:'/detail/'+scope.row.id}">详情</router-link>
          <!--scope.$index:获取索引,
             scope.row:获取所有数据
             scope.row.id:获取id,如果实现删除功能就写  @click="handleDelete(scope.row.id)
             -->
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="newsDelete(scope.row.id)">删除</el-button><!--scope.row.id:获取删除新闻id-->
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      background
      layout="prev, pager, next"
      @current-change="handPage"
      :page-size="pageSize"
      :current-page="pageNum"
      :total="total">
    </el-pagination>
     <!--新增和修改弹窗-->     
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>这是一段信息</span>
      <el-form ref="form" :model="news" label-width="80px">
        <el-form-item label="新闻标题">
          <el-input v-model="news.title"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容">
          <el-input type="textarea" v-model="news.content"></el-input>
        </el-form-item>
        <el-form-item label="发布人">
          <el-input v-model="news.publisher"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit(news)" icon="el-icon-plus">提交</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "List",
      data(){
          return{
            newsList:[],
            dialogVisible:false,//控制弹窗显示和隐藏
            news:{},
            pageSize:5,
            pageNum:1,
            total:0
          }
      },
      methods:{
        //分页查询
          getNewsPage(){
            //resultFull风格形式
            this.$axios.get("http://localhost:8081/news/page/"+this.pageNum+"/"+this.pageSize+"",{
            }).then((response)=>{
              //将查询的数据放到newsList中
              this.newsList=response.data.records
              this.total=response.data.total;
            })
              .catch(function (error) {
                console.log("=====>"+error)
              })
          },
        //当前页面改变重新查数据 点击上一页,下一页
        handPage(pageNum){
            this.pageNum=pageNum
            this.getNewsPage()
        },
       //处理新增
        newsAdd(){
          this.dialogVisible = true;
        },
       //新增新闻
        newsAdds(){
          this.$axios.post('http://localhost:8081/addNews', this.news)
            .then((response)=> {
              if (response.data===true){
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
                this.getNewsList();
              }
            })
        },
          //获取新闻类表
        getNewsList(){
          this.$axios.get("http://localhost:8081/news2",{
            //?号传参
            params:{
              title:null
            }

          }).then((response)=>{
            //将查询的数据放到newsList中
            this.newsList=response.data
          })
          .catch(function (error) {
            console.log("=====>"+error)
          })
        },
        //查询要修改的数据,从前端的row中获取
        handleEdit($index,row){
          this.dialogVisible=true
          this.news = row
        },

        // 定义提交事件判断是新增还是修改
        onSubmit:function (news) {
             if (news.id!=null){
                this.newsUpdate();
               this.news={};

             }else {
               this.newsAdds();
               this.news={};
               this.dialogVisible = false
             }
        },
        //修改方法
        newsUpdate(){
          this.$axios.post('http://localhost:8081/udpateNews', this.news)
            .then((response)=> {
              if (response.data===true){
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
               this.getNewsPage()
              }
            })
          //隐藏模态框
          this.dialogVisible = false
        },
        //删除操作
        newsDelete(id){
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              this.$axios.delete("http://localhost:8081/news/"+id+"")
                .then((res)=>{
                  if (res.data===true){
                    this.$message({
                      message: '删除成功',
                      type: 'success'
                    })
                    this.getNewsPage()
                  }else {
                    this.$message({
                      message: '删除失败',
                      type: 'success'
                    })
                  }
                })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }
      },
      mounted() {
          //默认时展示数据
          //this.getNewsList();
        //分页数据展示
        this.getNewsPage()
          //隐藏模态框
        this.dialogVisible=false;
      }
    }
</script>

<style scoped>

</style>

在components下新建一个news包下新建一个Details组件

<template>
  <div>
    <!--用于展示数据详情-->
    <table>
      <tr>
        <td>标题</td>
        <td>{{news.title}}</td>
      </tr>
      <tr>
        <td>发布人</td>
        <td>{{news.publisher}}</td>
      </tr>
      <tr>
        <td>发布时间</td>
        <td>{{news.createTime}}</td>
        <td></td>
      </tr>
    </table>
  </div>
</template>

<script>
    export default {
        name: "Details",
        data(){
          return {
            news:{}
          }
        },
       methods:{
         getNewsDetail(){
           const id = this.$route.params.id;
           console.log("====>"+id)
           this.$axios.get("http://localhost:8081/getById/"+id).then(res=>{
             this.news=res.data;
           })
         }
       },
      mounted() {
          this.getNewsDetail();
      }

    }
</script>

<style scoped>

</style>

后台代码

package com.ketai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ketai.pojo.News;
import com.ketai.service.NewsService2;
import com.ketai.vo.NewsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class NewsController {

    @Autowired
    private NewsService2 newsService2;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping("getById/{id}")
    public Object getById(@PathVariable Integer id){
        System.err.println("=============");
       return newsService2.getById(id);
    }

    /**
     * 添加新闻
     * @param news
     * @return
     */
    @PostMapping("addNews")
    public boolean addNews(@RequestBody News news){
        return newsService2.save(news);
    }

    /**
     * 根据标题模糊查询新闻
     */
    @RequestMapping("/news2")
    public List<News> getByTitle(@RequestParam(required = false) String title){
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.like(title!=null,"title",title);
        List<News> list = newsService2.list(wrapper);
        return  list;
    }
    /**
     * 查询id在5-10范围内的新闻
     */
    public List<News> list(){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.le("id",10);
        wrapper.ge("id","5");
        return newsService2.list(wrapper);
    }

    /**
     * 分页查询
     */
    @RequestMapping("/news/page/{pageNum}/{pageSize}")
    public Page<News> page(@PathVariable Integer pageNum,
                           @PathVariable Integer pageSize){

        //设置分页信息
        Page<News> page = new Page<>(pageNum,pageSize);
        Page<News> page1 = newsService2.page(page);
        ///System.out.println("分页数据:"+page1.getRecords());
        System.out.println("总页数"+page1.getPages());
        System.out.println("总记录数:"+page1.getTotal());
        System.err.println(page1.getCurrent());
        return page1;

    }

    /**
     * 根据id删除新闻
     */
    @RequestMapping("/news/{id}")
    public Object delete(@PathVariable Integer id){
        boolean b = newsService2.removeById(id);
   return b;
    }

    /**
     * 修改
     * @param news
     * @return
     */
   @RequestMapping("/udpateNews")
   public Object updateNews(@RequestBody News news){
       System.out.println(news);
    return newsService2.updateById(news);
   }




}

avatar

yuanyourdomain

写代码,做研究,记录生活。

RECOMMENDED

MyBatis 动态 SQL

2026-07-08

Nginx 基础入门

2026-07-08

Maven 多模块与私服

2026-07-08