ElementUI动态树,数据表格以及分页的实现

简介: ElementUI动态树,数据表格以及分页的实现

前言

在上一篇博客中实现了左侧菜单栏,在此基础上将它变为动态的,即动态的展示数据库的数据。还有数据表格的实现以及分页。(纯代码分享)

ElementUI官网https://element.eleme.cn/#/zh-CN/component/pagination

一. ElementUI动态树

LeftNav.vue

<template>
  <el-menu router :default-active="$route.path" default-active="2" class="el-menu-vertical-demo" background-color="#334157" text-color="#fff"
    active-text-color="#ffd04b" :collapse="collapsed">
    <div class="logobox">
      <img class="logoimg" src="../assets/img/logo.png" alt="">
    </div>
    <el-submenu v-for="m in menus" :index="'idx_'+m.id" :key="'key'+m.id">
      <template slot="title">
        <i :class="m.icon"></i>
        <span>{{m.text}}</span>
      </template>
      <el-menu-item v-for="m2 in m.modules" :index="m2.url" :key="'key'+m2.id">
        <i :class="m2.icon"></i>
        <span>{{m2.text}}</span>
      </el-menu-item>
    </el-submenu>
  </el-menu>
</template>
<script>
  export default {
    data() {
      return {
        collapsed: false,
        menus: []
      }
    },
    created() {
      this.$root.Bus.$on('aaa', v => {
        this.collapsed = v
      });
      let url = this.axios.urls.SYSTEM_MENUS;
      this.axios.get(url, {}).then(r => {
        console.log(r);
        this.menus = r.data.rows;
      }).catch(e => {
      });
    }
  }
</script>
<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 240px;
    min-height: 400px;
  }
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    border: none;
    text-align: left;
  }
  .el-menu-item-group__title {
    padding: 0px;
  }
  .el-menu-bg {
    background-color: #1f2d3d !important;
  }
  .el-menu {
    border: none;
  }
  .logobox {
    height: 40px;
    line-height: 40px;
    color: #9d9d9d;
    font-size: 20px;
    text-align: center;
    padding: 20px 0px;
  }
  .logoimg {
    height: 40px;
  }
</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import AppMain from '@/components/AppMain'
import LeftNav from '@/components/LeftNav'
import TopNav from '@/components/TopNav'
import Login from '@/views/Login'
import Register from '@/views/Register'
import AddBook from '@/views/book/AddBook'
import BookList from '@/views/book/BookList'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },{
      path: '/Register',
      name: 'Register',
      component: Register
    },{
      path: '/AppMain',
      name: 'AppMain',
      component: AppMain,
      children:[
        {
          path: '/LeftNav',
          name: 'LeftNav',
          component: LeftNav
        },{
          path: '/TopNav',
          name: 'TopNav',
          component: TopNav
        },{
          path: '/book/AddBook',
          name: 'AddBook',
          component: AddBook
        },{
          path: '/book/BookList',
          name: 'BookList',
          component: BookList
        }
      ]
    }
  ]
})

action.js

/**
 * 对后台请求的地址的封装,URL格式如下:
 * 模块名_实体名_操作
 */
export default {
  'SERVER': 'http://localhost:8080', //服务器
  'SYSTEM_USER_DOLOGIN': '/user/userLogin', //登陆
  'SYSTEM_USER_DOREG': '/user/userRegister', //注册
  'SYSTEM_MENUS': '/module/queryRootNode', //左侧菜单树
  'getFullPath': k => { //获得请求的完整地址,用于mockjs测试时使用
    return this.SERVER + this[k];
  }
}

展示效果:

二. 数据表格和分页

BookList.vue

<template>
  <div class="books" style="padding: 20px;">
    <!-- 搜索框 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="书籍名称">
        <el-input v-model="bookname" placeholder="书籍名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <template>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="编号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="bookname"
          label="书籍名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="price"
          label="书籍价格">
        </el-table-column>
        <el-table-column
          prop="booktype"
          label="书籍类别">
        </el-table-column>
      </el-table>
    </template>
    <!-- 分页 -->
     <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="rows"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        bookname:'',
        tableData:[],
        page:1,
        rows:10,
        total:0
      }
    },
    methods:{
      // 当前页大小
      handleSizeChange(r){
        let params = {
          bookname : this.bookname,
          rows : r,
          page : this.page
        }
        this.query(params);
        // 当前页码
      },handleCurrentChange(p){
        let params = {
          bookname : this.bookname,
          rows : this.rows,
          page : p
        }
        this.query(params);
      },
      query(params){
        let url = this.axios.urls.BOOK_LIST;
        this.axios.get(url, {params:params}).then(r => {
          console.log(r);
          this.tableData = r.data.rows;
          this.total = r.data.total;
        }).catch(e => {
        });
      },
      onSubmit(){
        let params = {
          bookname : this.bookname
        }
        this.query(params);
      }
    },
    created() {
      this.query({});
    }
  }
</script>
<style>
</style>

action.js

 'BOOK_LIST': '/book/queryBookPager', //数据表格

展示效果:

三. 后端代码

service层

IModuleService

package com.zking.ssm.service;
import com.zking.ssm.model.Module;
import com.zking.ssm.model.RoleModule;
import com.zking.ssm.model.TreeNode;
import com.zking.ssm.vo.RoleModuleVo;
import org.springframework.stereotype.Repository;
import java.util.List;
public interface IModuleService {
    List<Module> queryRootNode(Integer id);
    List<TreeNode> queryTreeNode(Integer id);
    int addRoleModule(RoleModule roleModule);
    List<String> queryModuleByRoleId(RoleModule roleModule);
}

ModuleServiceImpl

package com.zking.ssm.service.impl;
import com.zking.ssm.mapper.ModuleMapper;
import com.zking.ssm.mapper.RoleModuleMapper;
import com.zking.ssm.model.Module;
import com.zking.ssm.model.RoleModule;
import com.zking.ssm.model.TreeNode;
import com.zking.ssm.service.IModuleService;
import com.zking.ssm.vo.RoleModuleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ModuleServiceImpl implements IModuleService {
    @Autowired
    private ModuleMapper moduleMapper;
    @Autowired
    private RoleModuleMapper roleModuleMapper;
    @Override
    public List<Module> queryRootNode(Integer id) {
        return moduleMapper.queryChildNodeByPid(id);
    }
    @Override
    public List<TreeNode> queryTreeNode(Integer id) {
        return moduleMapper.queryTreeNodeByPid(id);
    }
    @Override
    public int addRoleModule(RoleModule roleModule) {
        roleModuleMapper.deleteRoleModule(roleModule);
        roleModuleMapper.insertRoleModule(roleModule);
        return 1;
    }
    @Override
    public List<String> queryModuleByRoleId(RoleModule roleModule) {
        return roleModuleMapper.queryModuleByRoleId(roleModule);
    }
}

IBookService

package com.zking.ssm.service;
import com.zking.ssm.model.Book;
import com.zking.ssm.util.PageBean;
import java.util.List;
import java.util.Map;
public interface IBookService {
    int deleteByPrimaryKey(Integer id);
    int insert(Book record);
    Book selectByPrimaryKey(Integer id);
    int updateByPrimaryKey(Book record);
    List<Book> queryBookPager(Book book, PageBean pageBean);
    Map<String,Object> queryBookCharts();
}

BookServiceImpl

package com.zking.ssm.service.impl;
import com.zking.ssm.mapper.BookMapper;
import com.zking.ssm.model.Book;
import com.zking.ssm.service.IBookService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class BookServiceImpl implements IBookService {
    @Autowired
    private BookMapper bookMapper;
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return bookMapper.deleteByPrimaryKey(id);
    }
    @Override
    public int insert(Book record) {
        return bookMapper.insert(record);
    }
    @Override
    public Book selectByPrimaryKey(Integer id) {
        return bookMapper.selectByPrimaryKey(id);
    }
    @Override
    public int updateByPrimaryKey(Book record) {
        return bookMapper.updateByPrimaryKey(record);
    }
    @Override
    public List<Book> queryBookPager(Book book, PageBean pageBean) {
        return bookMapper.queryBookPager(book);
    }
    @Override
    public Map<String, Object> queryBookCharts() {
        return bookMapper.queryBookCharts();
    }
}

controller层

ModuleController

package com.zking.ssm.controller;
import com.zking.ssm.model.Module;
import com.zking.ssm.model.RoleModule;
import com.zking.ssm.model.TreeNode;
import com.zking.ssm.service.IModuleService;
import com.zking.ssm.util.JsonResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/module")
public class ModuleController {
    @Autowired
    private IModuleService moduleService;
    @RequestMapping("/queryRootNode")
    @ResponseBody
    public JsonResponseBody<List<Module>> queryRootNode(){
        try {
            List<Module> modules = moduleService.queryRootNode(-1);
            return new JsonResponseBody<>("OK",true,0,modules);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("初始化首页菜单错误",false,0,null);
        }
    }
    @RequestMapping("/queryElementTree")
    @ResponseBody
    public JsonResponseBody<List<TreeNode>> queryElementTree(){
        try {
            List<TreeNode> modules = moduleService.queryTreeNode(-1);
            return new JsonResponseBody<>("OK",true,0,modules);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("初始化ElementUI的Tree组件错误",false,0,null);
        }
    }
    @RequestMapping("/addRoleModule")
    @ResponseBody
    public JsonResponseBody<?> addRoleModule(RoleModule roleModule){
        try {
            moduleService.addRoleModule(roleModule);
            return new JsonResponseBody<>("新增角色权限成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("新增角色权限失败",false,0,null);
        }
    }
    @RequestMapping("/queryModuleByRoleId")
    @ResponseBody
    public JsonResponseBody<List<String>> queryModuleByRoleId(RoleModule roleModule){
        try {
            List<String> modules = moduleService.queryModuleByRoleId(roleModule);
            return new JsonResponseBody<>("OK",true,0,modules);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("获取角色权限失败",false,0,null);
        }
    }
}

BookController

package com.zking.ssm.controller;
import com.zking.ssm.model.Book;
import com.zking.ssm.service.IBookService;
import com.zking.ssm.util.JsonResponseBody;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.vo.BookFileVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private IBookService bookService;
    @RequestMapping("/addBook")
    @ResponseBody
    public JsonResponseBody<?> addBook(Book book){
        try {
            bookService.insert(book);
            return new JsonResponseBody<>("新增书本成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("新增书本失败",false,0,null);
        }
    }
    @RequestMapping("/editBook")
    @ResponseBody
    public JsonResponseBody<?> editBook(Book book){
        try {
            bookService.updateByPrimaryKey(book);
            return new JsonResponseBody<>("编辑书本成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("编辑书本失败",false,0,null);
        }
    }
    @RequestMapping("/delBook")
    @ResponseBody
    public JsonResponseBody<?> delBook(Book book){
        try {
            bookService.deleteByPrimaryKey(book.getId());
            return new JsonResponseBody<>("删除书本成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("删除书本失败",false,0,null);
        }
    }
    @RequestMapping("/queryBookPager")
    @ResponseBody
    public JsonResponseBody<List<Book>> queryBookPager(Book book, HttpServletRequest req){
        try {
            PageBean pageBean=new PageBean();
            pageBean.setRequest(req);
            List<Book> books = bookService.queryBookPager(book, pageBean);
            return new JsonResponseBody<>("OK",true,pageBean.getTotal(),books);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("分页查询书本失败",false,0,null);
        }
    }
    @RequestMapping("/queryBookCharts")
    @ResponseBody
    public JsonResponseBody<?> queryBookCharts(){
        try{
            Map<String, Object> charts = bookService.queryBookCharts();
            return new JsonResponseBody<>("OK",true,0,charts);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResponseBody<>("查询统计分析数据失败",false,0,null);
        }
    }
    @RequestMapping("/upload")
    @ResponseBody
    public JsonResponseBody<?> upload(BookFileVo bookFileVo){
        try {
            MultipartFile bookFile = bookFileVo.getBookFile();
            System.out.println(bookFileVo);
            System.out.println(bookFile.getContentType());
            System.out.println(bookFile.getOriginalFilename());
            return new JsonResponseBody<>("上传成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("上传失败",false,0,null);
        }
    }
    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response){
        try {
            String relativePath = "uploads/1.jpg";
            String absolutePath = request.getRealPath(relativePath);
            InputStream is = new FileInputStream(new File(absolutePath));
            OutputStream out = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1.jpg", "UTF-8"));
            byte[] by = new byte[1024];
            int len = -1;
            while (-1 != (len = is.read(by))) {
                out.write(by);
            }
            is.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/downloadUrl")
    public void downloadUrl(HttpServletRequest request, HttpServletResponse response){
        String relativePath = "uploads/1.jpg";
        String absolutePath = request.getRealPath(relativePath);
        InputStream is = null;
        OutputStream out = null;
        try {
            is = new FileInputStream(new File(absolutePath));
            // 设置Content-Disposition
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("1.jpg", "UTF-8"));
            out = response.getOutputStream();
            IOUtils.copy(is, out);
            response.flushBuffer();
            System.out.println("完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(out);
        }
    }
}


相关文章
|
SQL 前端开发 API
关于ElementUI之动态树+数据表格+分页实例
关于ElementUI之动态树+数据表格+分页实例
178 0
|
JavaScript 数据库
Vue之ElementUI之动态树+数据表格+分页(项目功能)
Vue之ElementUI之动态树+数据表格+分页(项目功能)
132 0
|
SQL 前端开发 搜索推荐
【Element-UI】实现动态树、数据表格及分页效果
在现代软件开发中,动态树、数据表格以及分页效果成为了许多应用的核心需求。随着业务规模和复杂性的增加,我们往往需要展示大量的层级结构数据,并且实现交互性强且高效的操作。 动态树提供了一种组织结构清晰、可伸缩的展示方式,使用户可以方便地查看和操作树节点。数据表格则是以表格形式呈现数据,在其中用户可以进行排序、筛选、编辑等操作。 而分页效果则能够将大量数据分割成易于管理和浏览的一页或一页的内容。这三种功能的结合,不仅使得我们能够更好地处理庞大的数据集合,同时也使得用户能够快速定位所需信息。 本文将介绍如何使用现代前端技术实现动态树、数据表格及分页
|
JavaScript
Layui数据表格嵌套文件上传按钮
Layui数据表格嵌套文件上传按钮
206 0
layUI数据表格可编辑扩展下拉框
layUI数据表格可编辑扩展下拉框
189 0
|
11天前
|
前端开发 UED 开发者
React 数据表格分页实现
本文详细介绍了如何在React中实现数据表格的分页功能,包括基础实现、常见问题及解决方案。通过状态管理和事件处理,我们可以有效地减少页面加载时间,提升用户体验。文章提供了完整的代码示例,帮助开发者解决分页按钮样式、按钮过多和初始加载慢等问题,并给出了相应的优化方案。
90 53
|
前端开发 JavaScript API
在 Vue3 + Element Plus 中生成动态表格,动态修改表格,多级表头,合并单元格
在 Vue 中,表格组件是使用频率及复杂度排名第一的组件,前端经常需要根据后台返回的数据动态渲染表格,比如动态表格如何生成,因为表格的列并不是固定的,在未知表格具体有哪些列的场景下,前端如何动态渲染表格数据。又或者需要把表格单元格进行合并处理,比如第一列是日期,需要把相同的日期进行合并,这样表格看起来会更加清晰。 本文手把手教你如何在 Vue3 + Element Plus 中创建表格、生成动态表格、创建动态多级表头、表格行合并、列合并等问题。如果你正在搭建后台管理工具,又不想处理前端问题,推荐使用卡拉云 ,卡拉云是新一代低代码开发工具,可一键接入常见数据库及 API ,无需懂前端,仅需拖拽即
3095 0
|
5月前
|
API
9.SPA项目开发之动态树+数据表格+分页
9.SPA项目开发之动态树+数据表格+分页
46 0
|
前端开发 API 网络架构
Vue+ElementUI实现动态树和表格数据的分页模糊查询
Vue+ElementUI实现动态树和表格数据的分页模糊查询
165 0
|
11月前
ElementUI之动态树+数据表格+分页->动态树,动态表格
ElementUI之动态树+数据表格+分页->动态树,动态表格
43 0