Vue+axios 整合 layui+laypage實現真分頁

說明

  • Vue數據綁定
  • axios請求服務器端數據
  • layui提供表格樣式
  • laypage提供分頁

整合效果

在這裏插入圖片描述

代碼

創建項目,導入

在這裏插入圖片描述

服務器端代碼

  • 數據庫腳本
CREATE TABLE `tb_dept`  (
  `deptno` tinyint(2) UNSIGNED NOT NULL  COMMENT '部門編號',
  `dname` varchar(14) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部門名稱',
  `loc` varchar(13) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部門地址',
  PRIMARY KEY (`deptno`) USING BTREE
) ENGINE = InnoDB  CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  • Maven依賴
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.18</version>
</dependency>
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>
  • Dept.java
public class Dept {
    private Integer deptno;
    private String dname;
    private String loc;

    //……getter/setter、默認構造方法、全參構造方法
}
  • PageBean.java
public class PageBean<T> {
    /**
     * 每頁顯示的條數
     */
    private long pageSize = 10;
    /**
     * 當前的頁碼
     */
    private long pageNum;
    /**
     * 一共有多少條記錄
     */
    private long total;
    /**
     * 一共有多少頁
     */
    private long pages;
    /**
     * 每一頁所顯示的數據
     */
    private List<T> records;

    //……getter/setter、默認構造方法、全參構造方法
}
  • DBUtil.java
public final class DBUtil {
    private static final String url = "jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=GMT%2B8";//連接字符串
    private static final String name = "root";    //用戶名
    private static final String pass = "root"; //密碼

    static {// 1、加載驅動
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, name, pass);
    }
     public static void free(ResultSet rs, Statement stmt, Connection conn) {
        try { // 建議採用這種形式來釋放資源,因爲finally裏面的一定會被釋放
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
  • DeptService.java
public class DeptService {
    public List<Dept> getAll() throws SQLException {
        List<Dept> depts = new ArrayList<>();
        Connection conn = DBUtil.getConnection();
        String sql = "select * from tb_dept";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            depts.add(new Dept(rs.getInt("deptno"), rs.getString("dname"), rs.getString("loc")));
        }
        return depts;
    }

    public List<Dept> getWithPage(Integer pageNum, Integer pageSize) throws SQLException {
        List<Dept> depts = new ArrayList<>();
        Connection conn = DBUtil.getConnection();
        String sql = "select * from tb_dept limit ?,?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, (pageNum - 1) * pageSize);
        ps.setInt(2, pageSize);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            depts.add(new Dept(rs.getInt("deptno"), rs.getString("dname"), rs.getString("loc")));
        }
        DBUtil.free(rs,ps,conn);
        return depts;
    }

    public int count() throws SQLException {
        Connection conn = DBUtil.getConnection();
        String sql = "select count(*) from tb_dept";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        rs.next();
        int res = rs.getInt(1);
        DBUtil.free(rs,ps,conn);
        return res;
    }
}
  • DeptServlet
@WebServlet(urlPatterns = "/dept")
public class DeptServlet extends HttpServlet {

    private DeptService deptService = new DeptService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getParameter("op");
        PrintWriter out = resp.getWriter();
        switch (op) {
            case "getAll":
                try {
                    getAll(out);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case "getWithPage":
                try {
                    getWithPage(req, out);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
        out.flush();
    }

    private void getWithPage(HttpServletRequest req, PrintWriter out) throws SQLException {
        int pageNum = Integer.parseInt(req.getParameter("pageNum"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        List<Dept> depts = deptService.getWithPage(pageNum, pageSize);
        PageBean<Dept> pageBean = new PageBean<>();
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);
        pageBean.setRecords(depts);

        int count = deptService.count();
        pageBean.setTotal(count);
        pageBean.setPageSize(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        out.write(JSON.toJSONString(pageBean));
    }

    private void getAll(PrintWriter out) throws SQLException {
        List<Dept> depts = deptService.getAll();
        PageBean<Dept> pageBean = new PageBean<>();
        pageBean.setRecords(depts);
        out.write(JSON.toJSONString(pageBean));
    }
}

前端頁面代碼(★★★★★)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="layui/css/layui.css">
    </head>
    <body>
        <table class="layui-table" id="app">
            <thead>
                <tr>
                    <th>部門編號</th>
                    <th>部門名稱</th>
                    <th>部門地址</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="dept in deptList">
                    <td>{{dept.deptno}}</td>
                    <td>{{dept.dname}}</td>
                    <td>{{dept.loc}}</td>
                </tr>
            </tbody>
        </table>
        <div id="laypage"></div>


        <script src="layui/layui.js"></script>
        <script src="layui/jquery.js"></script>
        <script src="js/vue.js"></script>
        <script src="js/axios.min.js"></script>
        <script type="text/javascript">
            let vm = new Vue({
                el: "#app",
                data: { //函數對象:用來接收數據(數據承載模型)
                    deptList: [],
                    pageNum: 1, //設置首頁頁碼
                    pageSize: 10,  //設置一頁顯示的條數
                    total: 0,    //總條數
                    pages: 1 //一共多少頁
                },
                methods: {
                    getData: function () {
                        axios.get('dept', {
                            params: {
                                op: 'getWithPage',
                                pageNum: this.pageNum,
                                pageSize: this.pageSize
                            }
                        }).then(res => {
                            this.deptList = res.data.records;
                            this.total = res.data.total;  //設置總條數
                            this.pages = res.data.pages;
                            console.info(res);
                            if (this.pageNum == 1) {
                                this.showPage();
                            }
                        }).catch(error => {
                            console.log(error);
                        });
                    },
                    showPage: function () {
                        layui.use('laypage', function () {
                            let laypage = layui.laypage;
                            //執行一個laypage實例
                            laypage.render({
                                elem: 'laypage',  //注意laypage是 ID,不用加 # 號
                                count: vm.total, //數據總數,從服務端得到
                                limit: vm.pageSize,   //每頁條數設置
                                limits: [10, 20, 30],			//可選每頁顯示條數
                                curr: 1,                      //起始頁
                                groups: 3,                     //連續頁碼個數
                                prev: '上一頁',               //上一頁文本
                                next: '下一頁',                //下一頁文本
                                first: 1,                    //首頁文本
                                last: vm.pages,                   //尾頁文本
                                layout: ['prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                                jump: function (obj, first) {  //觸發分頁後的回調
                                    //obj包含了當前分頁的所有參數,第一次加載first爲true
                                    console.log(obj.curr); //得到當前頁,以便向服務端請求對應頁的數據。
                                    console.log(obj.limit); //得到每頁顯示的條數
                                    vm.pageNum = obj.curr;  //改變當前頁碼
                                    vm.pageSize = obj.limit;
                                    //首次不執行,一定要加此判斷,否則初始時會無限刷新
                                    if (!first) {
                                        vm.getData();  //加載數據
                                    }
                                }
                            });
                        });
                    }
                },
                created: function () {
                    this.getData();
                }
            });
        </script>
    </body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章