利用localStorage做一个类似于购物车的功能
一、利用localStorage做一个类似与购物车功能的效果,具体如下图把选中的列表点击添加到配置,那么选中的那些用户变成取消配置状态,批量配置里面有相应的选中用户进行配置。
(1)页面已加载完成就判断localStorage是否有选中待配置的数据,有就弹框让用户选择是否继续配置
mounted:function(){
//配置列表中的用户
this.choosedUser = JSON.parse(window.localStorage.getItem("choosedConfig"));
if(this.choosedUser== null){
this.choosedUser = [];
}else{
this.choosedUser =JSON.parse(window.localStorage.getItem("choosedConfig"))
if(this.choosedUser.length!=0){
this.Surevisible = true;
this.divinfo = {
title:'当前有'+this.choosedUser.length+'个用户待批量配置,是否进行配置?',
divin:''
}
}
}
}
(2)首先定义一个数组和当前列表的每页展示的数据长度一样即长度为10的都是false默认显示添加到配置的状态
/*公用函数 用于切换添加和取消配置
userList:当前页用户列表数据
choosedUser:添加到批量配置的数据
isTrue:控制显示 true显示添加到配置 false显示取消配置
config:存储isTrue的数组
*/
checkConfig(userList,choosedUser,isTrue,config){
for(var i=0;i< userList.length;i++){
config[i] = true;
for(var j=0;j<choosedUser.length;j++){
if(userList[i].ID ==choosedUser[j].ID){
config[i] = isTrue;
}
}
}
return config
},
//在获取用户列表的时候初始化一个长度为10的全是fasle的数组
getUserListData(e){
var $that = this;
GetUserList(e).then(function(res){
if(res.data.StatusCode=="10000000"){
$that.userList = res.data.Data.dataInfo;
$that.TotalCount = res.data.Data.TotalCount;
$that.pageCount = res.data.Data.pageCount;
//判断状态的数组
$that.config = $that.checkConfig( $that.userList,$that.choosedUser,false,$that.config);
}
})
}
(3)点击添加到批量配置要合并所有的目前已选中的用户,注意:
要去重否则已经在批量配置里面的数据会重复添加
//添加到批量配置
addConfig(){
if(this.selectedUser.length==0){
this.$message({
message:'请选择要添加到批量配置的用户',
duration:1000
});
}else{
this.$message({
message: '已成功的添加到批量配置',
type: 'success',
duration:1000
});
//合并
this.choosedUser = this.choosedUser.concat(this.selectedUser);
//去重
let hash = {};
this.choosedUser = this.choosedUser.reduce((preVal, curVal) => {
hash[curVal.ID] ? '' : hash[curVal.ID] = true && preVal.push(curVal);
return preVal
}, [])
window.localStorage.setItem("choosedConfig",JSON.stringify(this.choosedUser))
//显示取消配置
this.config = this.checkConfig( this.userList,this.choosedUser,false,this.config);
//刷新数据 页面才有转换添加配置和取消配置的状态
this.getUserListData(this.params);
}
},