目录

一、Element概述

二、Element快速入门

三、Element布局

 四、Element组件

五、综合案例

5.1 查询所有

5.2 新增品牌

5.3 Servlet代码优化

5.4 修改品牌

5.5 删除品牌 

5.6 批量删除

5.7 分页查询

5.8 条件查询


一、Element概述

element table分组_element table分组

二、Element快速入门

三、Element布局

element table分组_element table分组_02

 四、Element组件

 

element table分组_前端_03

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!--表单CSS样式-->
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->
    <el-row>
        <el-button type="danger" plain disabled>批量删除</el-button>
        <el-button type="primary" plain  @click="dialogVisible = true">新增</el-button>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%">
        <el-form ref="form" :model="brand" label-width="80px">

            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange">
            <!--复选框-->
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <!--序列-->
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    label="排序"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="当前状态"
                    align="center">
            </el-table-column>

            <el-table-column
                    label="操作"
                    align="center">
                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>
            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script>
    new Vue({
        el: "#app",
        methods: {
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },

            //复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;
                /*打印*/
                console.log(this.multipleSelection)
            },

            //查询方法
            onSubmit() {
                console.log(this.brand);
            },

            //添加数据
            addBrand(){
                console.log(this.brand);
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
            }
        },
        data() {
            return {
                //当前页码
                currentPage: 4,

                //添加数据对话框是否展示的标记
                dialogVisible:false,

                //品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },

                //复选框选中数据集合
                multipleSelection: [],

                //表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status:'1'
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status:'1'
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status:'1'
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status:'1'
                }]
            }
        }
    })

</script>

</body>
</html>

五、综合案例

element table分组_前端_04

5.1 查询所有

element table分组_java_05

                                                                 Dao层:

Mapper接口:

public interface BrandMapper {

    /**
     * 查询所有
     * @return
     */
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

}

BrandMapper.xlm: 

<mapper namespace="com.itheima.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result property="brandName" column="brand_name" />
        <result property="companyName" column="company_name" />
    </resultMap>
</mapper>

 brand实体类:

package com.itheima.pojo;

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }
    //逻辑视图
    public String getStatusStr(){
        if (status == null){
            return "未知";
        }
        return status == 0 ? "禁用":"启用";
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

                                                                Service层

BrandService接口:

public interface BrandService {
    /**
     * 查询所有
     * @return
     */
    List<Brand> selectAll();

}

接口实现类:

public class BrandServiceImpl implements BrandService {
    //1.创建SqlSessionFactory工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    @Override
    public List<Brand> selectAll() {

         //2.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();

        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        List<Brand> brands = mapper.selectAll();

        //5.释放资源
        sqlSession.close();

        return brands;
    }
}

Web层

Servlet:

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {

    private BrandService brandService = new BrandServiceImpl();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.调用service查询
        List<Brand> brands = brandService.selectAll();

        //2.将数据转为JSON
        String jsonString = JSON.toJSONString(brands);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

 Vue:

mounted(){
            //当页面加载完成后,发送异步请求来获取数据
            var _this = this;
            axios({
                method:"get",
                url:"http://localhost:8080/brand-case/selectAllServlet"
            }).then(function (resp){
                _this.tableData = resp.data;
            })

        }

5.2 新增品牌

element table分组_vue.js_06

Dao层 

BrandMapper接口: 

/**
     * 添加数据
     * @param brand
     */
    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

 Service层

service接口: 

/**
     * 添加品牌数据
     * @param brand
     */
    void add(Brand brand);

 service接口实现方法:

@Override
    public void add(Brand brand) {
        //2.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();

        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.add(brand);

        //5.提交事务
        sqlSession.commit();

        //6.释放资源
        sqlSession.close();
    }

Web层

AddServlet类: 

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {

    private BrandService brandService = new BrandServiceImpl();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.接受品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);

        //2.调用service添加
        brandService.add(brand);

        //3.响应成功的标识
        response.getWriter().write("success");

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

 Vue:

//查询所有数据
            selectAll(){
                //当页面加载完成后,发送异步请求来获取数据
                var _this = this;
                axios({
                    method:"get",
                    url:"http://localhost:8080/brand-case/selectAllServlet"
                }).then(function (resp){
                    _this.tableData = resp.data;
                })
            }
// 添加数据
            addBrand(){
                //console.log(this.brand);
                var _this = this;
                //发送ajax请求,添加数据
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/addServlet",
                    data:_this.brand
                }).then(function (resp){
                    if(resp.data == "success"){
                        //添加成功

                        //关闭窗口
                        _this.dialogVisible = false;

                        //重新查询数据
                        _this.selectAll();

                        //弹出消息提示
                        _this.$message({
                            showClose: true,
                            message: '恭喜你,添加成功',
                            type: 'success'
                        });
                    }
                })

            }

5.3 Servlet代码优化

element table分组_element table分组_07

 BaseServlet:

package com.itheima.web.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 替换HtttpServlet,根据请求的最后一段路径,进行方法分发
 */

public class BaseServlet extends HttpServlet {

    //根据资源路径进行方法分发
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求路径
        String requestURI = req.getRequestURI();//URI="/brand-case/brand/selectAll"

        //2.获取最后一段路径
        int index = requestURI.lastIndexOf("/");//从后面开始找,找到第一个出现字符为"/"并截取其后的字符串(包含/)
        String methodName = requestURI.substring(index+1);//select

        //3.执行方法
        //3.1获取BrandService/UserService 字节码对象 .class
            //谁调用我(this所在的方法),我(this)代表谁
            //this代表BrandServlet
        Class<? extends BaseServlet> cls = this.getClass();

        //3.2获取方法Method对象
        try {
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //3.3执行方法
            method.invoke(this, req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}

 BrandServlet:

@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{

    private BrandService brandService = new BrandServiceImpl();

    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.调用service查询
        List<Brand> brands = brandService.selectAll();

        //2.将数据转为JSON
        String jsonString = JSON.toJSONString(brands);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接受品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);

        //2.调用service添加
        brandService.add(brand);

        //3.响应成功的标识
        response.getWriter().write("success");
    }
}

5.4 修改品牌

5.5 删除品牌 

Dao层

/**
     * 根据id删除
     * @param id
     */
    @Delete("delete from tb_brand where id = #{id}")
    void deleteById(int id);

 Service层

BrandService接口:

/**
     * 单个删除
     * @param id
     */
    void deleteById(int id);

 BrandMapper实现类:

@Override
    public void deleteById(int id) {
        //2.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();

        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.deleteById(id);

        //5.提交事务
        sqlSession.commit();

        //6.释放资源
        sqlSession.close();
    }

Web层 

BrandServlet:

/**
     * 单个删除
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.获取要删除的id,获取data中的数据
        BufferedReader br = request.getReader();
        String _id = br.readLine();//json字符串

        System.out.println(_id);
        //转为int数据
        int id = JSON.parseObject(_id,int.class);

        //2.调用service添加
        brandService.deleteById(id);

        //3.响应成功的标识
        response.getWriter().write("success");
    }

 前端:

<el-row slot-scope="scope">
      <el-button type="danger" @click="deleteById(scope.row)">删除</el-button>
 </el-row>
// 单个删除
            deleteById(row){
                //弹出确认的提示框
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    //1.获取id
                    var _this = this;
                    //发送ajax请求,添加数据
                    axios({
                        method:"post",
                        url:"http://localhost:8080/brand-case/brand/deleteById",
                        data:row.id
                    }).then(function (resp){
                        if(resp.data == "success"){
                            //删除成功
                            //重新查询数据
                            _this.selectAll();
                            //弹出消息提示
                            _this.$message({
                                showClose: true,
                                message: '恭喜你,删除成功',
                                type: 'success'
                            });
                        }
                    })
                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

根据id删除可以采用Post,也可以采用Get,上述为采用post提交方式,通过data传递id数据

以下为采用get方式:

BrandServlet中需要修改

//1.获取要删除的id,获取data中的数据
        BufferedReader br = request.getReader();
        String _id = br.readLine();//json字符串

        System.out.println(_id);
        //转为int数据
        int id = JSON.parseObject(_id,int.class);

为:

//1.获取要删除的id,获取data中的数据
        String _id = request.getParameter("id");

        //转为int数据
        int id = Integer.parseInt(_id);

前端页面中:修改

axios({
       method:"post",
       url:"http://localhost:8080/brand-case/brand/deleteById",
       data:row.id
     })

 为

axios({
       method:"get",
       url:"http://localhost:8080/brand-case/brand/deleteById?id="+row.id
      })

补充知识:

用到显示表格时,当前行数据的获取也会用到插槽,例如

<el-table>
	<el-table-column width="150" align="center" label="Status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{scope.row.status}}</el-tag>
        </template>
      </el-table-column>
  </el-table>

scope相当于一行的数据, scope.row相当于当前行的数据对象。这里就是用插槽 拿到当前行 row是个内置的属性 ,vue slot的scope传递值是父作用域中的源数据改变,值会同步改变。且{{scope.$index}}可以获取当前行的index。

<slot :row="item" :$index="i"></slot>//index可以用来设置index   :row 可以设置行内内置对象

5.6 批量删除

element table分组_java_08

Dao层 

BrandMapper接口:

/**
     * 批量删除
     * @param ids
     */
    void deleteByIds(@Param("ids") int[] ids);

 BrandMapper.xml:

<delete id="deleteByIds">
        delete from tb_brand where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

Service层

BrandMapper接口:

/**
     * 批量删除
     * @param ids
     */
    void deleteByIds(int[] ids);

 BrandMapper实现接口:

@Override
    public void deleteByIds(int[] ids) {
        //2.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();

        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.deleteByIds(ids);

        //5.提交事务
        sqlSession.commit();

        //6.释放资源
        sqlSession.close();
    }

Web层

BrandServlet: 

/**
     * 批量删除
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接受品牌数据,Json格式[1,2,3]
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为int数据
        int[] ids = JSON.parseObject(params, int[].class);

        //2.调用service添加
        brandService.deleteByIds(ids);

        //3.响应成功的标识
        response.getWriter().write("success");
    }

 Vue:

方法:

// 批量删除
            deleteByIds(){

                //弹出确认的提示框
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮

                    //1.创建id数组[1,2,3],从this.multipleSelection获取即可
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        //定义一个对象数组接收multipleSelection[i]对象
                        //let selectionElement = this.multipleSelection[i];
                        this.selectedIds[i] = this.multipleSelection[i].id;
                    }
                    var _this = this;
                    //发送ajax请求,添加数据
                    axios({
                        method:"post",
                        url:"http://localhost:8080/brand-case/brand/deleteByIds",
                        data:_this.selectedIds
                    }).then(function (resp){
                        if(resp.data == "success"){

                            //删除成功
                            //重新查询数据
                            _this.selectAll();

                            //弹出消息提示
                            _this.$message({
                                showClose: true,
                                message: '恭喜你,删除成功',
                                type: 'success'
                            });
                        }
                    })
                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }

数据:

//被选中的id数组
                selectedIds:[],

5.7 分页查询

element table分组_vue.js_09

-- 分页查询 limit
-- 参数1:开始查询的索引
-- 参数2:查询的条目数

select * from tb_brand limit 0,5

select * from tb_brand limit 5,5


-- 页面传递的参数
-- 当前页码
-- 每页显示的条数

-- 参数1:开始索引 = (当前页码-1) * 每页显示条数
-- 参数2:查询的条目数 = 每页显示条数

PageBean实体类:

package com.itheima.pojo;


import java.util.List;

//分页查询的JavaBean
public class PageBean <T>{

    //总记录数
   private int totalCount;

   //当前页数据,自定义泛型<T>
    private List<T> rows;

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }
    
}

element table分组_vue.js_10

Dao层 

BrandMapper 接口:

/**
     * 分页查询
     * @param begin
     * @param size
     * @return
     */
    @Select("select * from tb_brand limit #{begin},#{size}")
    @ResultMap("brandResultMap")
    List<Brand> selectByPage(@Param("begin") int begin,@Param("size")int size);

    /**
     * 查询总记录数
     * @return
     */
    @Select("select count(*) from tb_brand")
    int selectTotalCount();

Service层:

BrandService接口:

/**
     * 分页查询
     * @param currentPage  当前页码
     * @param pageSize   每页展示条数
     * @return
     */
    PageBean<Brand> selectByPage(int currentPage,int pageSize);

 BrandService实现类:

@Override
    public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
        //2.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();

        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.计算开始索引
        int begin = ( currentPage - 1) * pageSize;
        //计算查询条目数
        int size = pageSize;

        //5.查询当前页数据
        List<Brand> rows = mapper.selectByPage(begin, size);

        //6.查询总记录数
        int totalCount = mapper.selectTotalCount();

        //7.封装PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        //8.释放资源
        sqlSession.close();

        return pageBean;
    }

Web层:

BrandServlet:

/**
     * 分页查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接受 当前页码 和 每页展示条数  url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
        //转为int类型
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        //2.调用service查询
        PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);

        //2.将数据转为JSON
        String jsonString = JSON.toJSONString(pageBean);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);

    }

 Vue:

//查询分页数据
            selectAll(){
                var _this = this;
                axios({
                    method:"get",
                    //拼字符串,换成模型,使之变为动态数据
                url:"http://localhost:8080/brand-case/brand/selectByPage?currentPage="+_this.currentPage+"&pageSize="+_this.pageSize
                }).then(function (resp){
                    //设置表格数据
                    _this.tableData = resp.data.rows;//{rows:[],totalCount:100}
                    //设置总记录数
                    _this.totalCount = resp.data.totalCount;
                    console.log(_this.totalCount );


                })
            }
//分页
            handleSizeChange(val) {
                //console.log(`每页 ${val} 条`);
                //重新设置每页显示的条数
                this.pageSize = val;
                this.selectAll();
            }
            handleCurrentChange(val) {
                //console.log(`当前页: ${val}`);
                //重新设置当前页码
                this.currentPage = val;
                this.selectAll();
            }

数据:

//每页显示的条数
                pageSize:5,//默认
                //总记录数
                totalCount:100,//默认
                // 当前页码
                currentPage: 1,//默认

5.8 条件查询

element table分组_vue.js_11

element table分组_element table分组_12

 Dao层

 BrandMapper接口:

/**
     * 分页条件查询
     * @param begin
     * @param size
     * @param brand
     * @return
     */
    List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size")int size,@Param("brand")Brand brand);

    /**
     * 根据条件查询总记录数
     * @return
     */
    int selectTotalCountByCondition(Brand brand);

BrandMapper.xml:

<select id="selectByPageAndCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <if test="brand.brandName != null and brand.brandName != '' ">
                and brand_name like #{brand.brandName}
            </if>

            <if test="brand.companyName != null and brand.companyName != '' ">
                and company_name like #{brand.companyName}
            </if>

            <if test="brand.status != null">
                and status like #{brand.status}
            </if>
        </where>

        limit #{begin},#{size}

    </select>


    <!--resultType定义返回值类型-->
    <select id="selectTotalCountByCondition" resultType="java.lang.Integer">
        select count(*)
        from tb_brand
        <where>
            <if test="brandName != null and brandName != '' ">
                and brand_name like #{brandName}
            </if>

            <if test="companyName != null and companyName != '' ">
                and company_name like #{companyName}
            </if>

            <if test="status != null">
                and status like #{status}
            </if>
        </where>
    </select>

Service层

BrandService接口:

/**
     * 分页条件查询
     * @param currentPage
     * @param pageSize
     * @param brand
     * @return
     */
    PageBean<Brand> selectByPageAndCondition(int currentPage,int pageSize,Brand brand);

 BrandService实现类:

@Override
    public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
        //2.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();

        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.计算开始索引
        int begin = ( currentPage - 1) * pageSize;
        //计算查询条目数
        int size = pageSize;


        //处理brand条件,模糊表达式
        String brandName = brand.getBrandName();
        if (brandName != null && brandName.length() > 0) {
            brand.setBrandName("%" + brandName + "%");
        }

        String companyName = brand.getCompanyName();
        if (companyName != null && companyName.length() > 0) {
            brand.setCompanyName("%" + companyName + "%");
        }

        //5.查询当前页数据
        List<Brand> rows = mapper.selectByPageAndCondition(begin, size,brand);

        //6.查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(brand);

        //7.封装PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        //8.释放资源
        sqlSession.close();

        return pageBean;
    }

Web层

BrandServlet:

/**
     * 分页条件查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接受 当前页码 和 每页展示条数  url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
        //转为int类型
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        //获取对应的查询条件对象
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串

        //转为Brand
        Brand brand = JSON.parseObject(params, Brand.class);

        //2.调用service查询
        PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage, pageSize,brand);

        System.out.println(pageBean);
        //2.将数据转为JSON
        String jsonString = JSON.toJSONString(pageBean);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);

    }

 Vue:

//查询分页数据
            selectAll(){
               /* //当页面加载完成后,发送异步请求来获取数据
                var _this = this;
                axios({
                    method:"get",
                    url:"http://localhost:8080/brand-case/brand/selectAll"
                }).then(function (resp){
                    //console.log(resp.data);
                    _this.tableData = resp.data;
                })*/
                var _this = this;
                axios({
                    method:"post",
                    //拼字符串,换成模型,使之变为动态数据
                    url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
                    data:this.brand//请求体数据json类型
                }).then(function (resp){
                    //设置表格数据
                    _this.tableData = resp.data.rows;//{rows:[],totalCount:100}
                    //设置总记录数
                    _this.totalCount = resp.data.totalCount;
                    //console.log(_this.totalCount );
                })
            }

前端代码优化:"=>"后可直接用this来表示vue对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->
    <el-row>
        <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
            >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>

            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="statusStr"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="js/axios-0.18.0.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">


<script>
    new Vue({
        el: "#app",


        /*加载完成后*/
        mounted(){
            //当页面加载完成后,发送异步请求来获取数据
            this.selectAll();
            /*var _this = this;
            axios({
                method:"get",
                url:"http://localhost:8080/brand-case/selectAllServlet"
            }).then(function (resp){
                _this.tableData = resp.data;
            })*/


        },


        /*方法区*/
        methods: {

            //查询分页数据
            selectAll(){
               /* //当页面加载完成后,发送异步请求来获取数据
                var _this = this;
                axios({
                    method:"get",
                    url:"http://localhost:8080/brand-case/brand/selectAll"
                }).then(function (resp){
                    //console.log(resp.data);
                    _this.tableData = resp.data;
                })*/

                /*var _this = this;
                axios({
                    method:"post",
                    //拼字符串,换成模型,使之变为动态数据
                    url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
                    data:this.brand//请求体数据json类型
                }).then(function (resp){
                    //设置表格数据
                    _this.tableData = resp.data.rows;//{rows:[],totalCount:100}
                    //设置总记录数
                    _this.totalCount = resp.data.totalCount;
                    //console.log(_this.totalCount );
                })*/
                var _this = this;
                axios({
                    method:"post",
                    //拼字符串,换成模型,使之变为动态数据
                    url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
                    data:this.brand//请求体数据json类型
                }).then(resp =>{
                    //设置表格数据
                    this.tableData = resp.data.rows;//{rows:[],totalCount:100}
                    //设置总记录数
                    this.totalCount = resp.data.totalCount;
                })

            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },

            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;
                //console.log(this.multipleSelection)
            },

            // 查询方法
            onSubmit() {
                //console.log(this.brand);
                this.selectAll();
            },

            // 添加数据
            addBrand(){
                //console.log(this.brand);
                var _this = this;
                //发送ajax请求,添加数据
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/brand/add",
                    data:_this.brand
                }).then(function (resp){
                    if(resp.data == "success"){
                        //添加成功

                        //关闭窗口
                        _this.dialogVisible = false;

                        //重新查询数据
                        _this.selectAll();

                        //弹出消息提示
                        _this.$message({
                            showClose: true,
                            message: '恭喜你,添加成功',
                            type: 'success'
                        });
                    }
                })
            },


            // 批量删除
            deleteByIds(){
                //弹出确认的提示框
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    //1.创建id数组[1,2,3],从this.multipleSelection获取即可
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        //定义一个对象数组接收multipleSelection[i]对象
                        //let selectionElement = this.multipleSelection[i];
                        this.selectedIds[i] = this.multipleSelection[i].id;
                    }
                    var _this = this;
                    //发送ajax请求,添加数据
                    axios({
                        method:"post",
                        url:"http://localhost:8080/brand-case/brand/deleteByIds",
                        data:_this.selectedIds
                    }).then(function (resp){
                        if(resp.data == "success"){
                            //删除成功
                            //重新查询数据
                            _this.selectAll();
                            //弹出消息提示
                            _this.$message({
                                showClose: true,
                                message: '恭喜你,删除成功',
                                type: 'success'
                            });
                        }
                    })
                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //分页
            handleSizeChange(val) {
                //console.log(`每页 ${val} 条`);
                //重新设置每页显示的条数
                this.pageSize = val;
                this.selectAll();
            },
            handleCurrentChange(val) {
                //console.log(`当前页: ${val}`);
                //重新设置当前页码
                this.currentPage = val;
                this.selectAll();
            },
        },


        /*数据区*/
        data() {
            return {
                //每页显示的条数
                pageSize:5,
                //总记录数
                totalCount:100,
                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },

                //被选中的id数组
                selectedIds:[],

                // 复选框选中数据集合
                multipleSelection: [],

                // 表格数据
                tableData: []
            }
        }
    })

</script>

</body>
</html>