前端用于低代码平台以及编辑器类项目的开发场景逐渐增多,对于这类项目除去复制粘贴功能以外 ,一般还需要有撤销与恢复的功能。本片文章大致内容就是如何设计一个用户历史操作记录的队列,去便于更好的实现用户编辑的前进后退。
假设用户进行添加数据操作
我们创建用户历史操作记录的队列可以有以下两种创建方式:
方式1:['a', 'ab' , 'abc']
方式2:['a', 'b' , 'c']
方式3:[ {type: 'add" value: 'a'}, {type: 'add" value: 'b'}, {type: 'add" value: 'c'} ]
对于这三种方式的选择:
首先我们要考虑这个项目的具体类型,用户操作是否是单一的操作类型、数据量是否庞大。
方式一适用于操作类型单一且数据量小。
方式二适用于操作类型单一且数据量大。
方式三适用于操作类型复杂且数据量大。
在我运营到的项目中、操作类型不单一且数据量大。以下我们考虑方式3如何去实现。
首先根据项目的操作自定义操作类型:撤销、复原、恢复等等。在用户后退或前进时,我们可以根据上一步修改的数据,进行对应的恢复,或者逆向修改。
历史队列具体实现思路:
首先我们创建一个历史记录类,用一个数组保存数据,用一个变量为指针,指向用户当前的最新操作。
指针默认指向用户最新操作
用户后退,指针后退
用户前进,指针前进
后退后再添加记录,删除当前指针后面的元素,再添加新的记录
我是在vuex进行创建,代码具体实现如下:
//store.jslet state = {/* 资源&数据 */historyStore:[], //撤销之前的操作historyIndex:-1,};
//action.js// 新增记录addItem(context,d) {// 撤销后重新添加记录 删除撤销的记录let arr = JSON.parse(JSON.stringify(context.state.historyStore))if (context.state.historyIndex != JSON.parse(JSON.stringify(context.state.historyStore)).length - 1) {context.commit("spliceHistoryStore",arr);}// 新增记录context.state.historyStore.push(JSON.parse(JSON.stringify(d)))context.state.historyIndex++;},// 后退back(context) {if (context.state.historyStore.length == 0 || context.state.historyIndex <= 0) return;context.state.historyIndex--;let currentPage = context.state.historyStore[context.state.historyIndex]if (currentPage.baseWidth !== undefined) {return;}currentPage.menuList.forEach((menu) => {if (!menu.id) {menu.id = $util.uuid();}});return new Promise((resolve, reject) => {$http.ajax({type: "post",url: baseUrl + "/edit/batchSaveOrUpdatePageInfo",contentType: "application/json; charset=UTF-8",data: JSON.stringify(currentPage),dataType: "json",success: function (data) {if (data.result) {// context.dispatch('getPageList')context.commit("setPageInfo", data.data);resolve();} else {layer.msg(data.desc);reject();}},error: function (data) {console.info(data);reject();},});});},// 前进go(context) {if (context.state.historyStore.length == 0 || context.state.historyIndex >= context.state.historyStore.length - 1) return;context.state.historyIndex++;let currentPage = context.state.historyStore[context.state.historyIndex]if (currentPage.baseWidth !== undefined) {return;}currentPage.menuList.forEach((menu) => {if (!menu.id) {menu.id = $util.uuid();}});return new Promise((resolve, reject) => {$http.ajax({type: "post",url: baseUrl + "/edit/batchSaveOrUpdatePageInfo",contentType: "application/json; charset=UTF-8",data: JSON.stringify(currentPage),dataType: "json",success: function (data) {if (data.result) {// context.dispatch('getPageList')context.commit("setPageInfo", data.data);resolve();} else {layer.msg(data.desc);reject();}},error: function (data) {console.info(data);reject();},});});},
具体业务逻辑自己替换。
上一篇:SQL语句性能分析
下一篇:tcp和udp有什么区别