layui table filter column is not reset with page refresh

Layui table has its own filter column function, but this filter column will be reset as the page is refreshed. When the user enters the page for the second time or manually renders the table, the filter items will be reset.
In this example, the local storage that comes with layui is used to save the data of the filter column, so as to achieve the effect that refreshing the page will not reset the filter column.

A project that can be fully run only by changing the import path.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Layui</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link rel="stylesheet" type="text/css" href="css/layui.css" />
		<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
	</head>
	<body>
		<!-- 显示 -->
		<table class="layui-hide" id="toolbar" lay-filter="toolbar"></table>

		<script src="layui.js" type="text/javascript" charset="utf-8"></script>
		<script src="lay/jquery-3.2.1.min.js" type="text/javascript" charset="utf-8"></script>
		<!-- 注意:如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
		<script>
			layui.use(['table', 'form'], function() {
				var table = layui.table;
				var $ = layui.$; //等同于jquery
				var form = layui.form;
				var cols = layui.data('cols').toolbar; //从存储中获取列记录
				if (cols == undefined) {
					cols = [{
						type: 'checkbox',
						fixed: 'left'
					}, {
						field: 'id',
						title: 'ID',
						width: 80,
						fixed: 'left',
						unresize: true,
						sort: true
					}, {
						field: 'username',
						title: '用户名',
						width: 120,
						edit: 'text',
					}, {
						field: 'email',
						title: '邮箱',
						width: 150,
						edit: 'text',
					}, {
						field: 'sex',
						title: '性别',
						width: 80,
						edit: 'text',
						sort: true,
					}]
				}
				table.render({
					elem: '#toolbar',
					url: '/test/table/demo1.json',
					toolbar: '#toolbar', //开启头部工具栏,并为其绑定左侧模板
					defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
						title: '提示',
						layEvent: 'LAYTABLE_TIPS',
						icon: 'layui-icon-tips'
					}],
					title: '用户数据表',
					cols: [cols],
					page: true
				});
				//工具栏事件监听
				table.on('toolbar(toolbar)', function(obj) {
					switch (obj.event) {
						case 'LAYTABLE_COLS': //筛选列点击事件
							setCols(obj);
							break;
					}
				})
				//保存筛选列
				function setCols(obj) {
					//点击筛选列面板里checkbox时保存
					layui.$(".layui-form-checkbox").click(function() {
						var cols = obj.config.cols[0]; //这里获取的是一个对象数组,保存了表格渲染时配置的列
						layui.data('cols', {
							key: obj.config.id,
							value: cols
						})
					})
				}
			});
		</script>
	</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_44285250/article/details/118183179