目录Vuex存储数组(新建,增,删,更新),并存入localstorage定时删除使用背景store中实现增删改组件中维护数组,进行判断存入localstorage并设置定时删除自定
初始化一个完整数组,但在业务逻辑中会单独更新或增删其中的一部分或全部。
如果每次都是全部更新,直接使用set替换即可,但大部分数组不变只修改个别数据,直接替换的代价较大,因此维护一个增删改的业务。
原来的数据都是有意义的,新数据可能是初始化的,不能直接替换成新数据,新数据可能只是增删了id,但是其他数据内容还要继续使用旧数据的,所以只能在旧数据基础上进行维护
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
list: [],
},
getters: {},
mutations: {
setList(state, list) {
state.list = list;
},
addItem(state, item) {
state.list.push(item);
},
updateItem(state, payload) {
Vue.set(state.list, payload.index, payload.data);
},
deleteItem(state, lt) {
let newIds = lt.map((item) => item.aid);
state.list = state.list.filter((item) => newIds.includes(item.aid));
},
},
actions: {}
})
export default store;
对象数组数据格式
[
{ "aid": "1", "aname": "111", "tobid": "1" }
{ "aid": "2", "aname": "DDD", "tobid": "2" }
]
组件中判断
自行修改使用:大更新需要add和delete,局部更新只有update
例如旧数组是【1,2】,新数组是【2,3】,经过第二步之后,旧数据变为【1,2,3】,但【1】是需要删除的
<template>
<div class="fORM-all">
<el-button @click="getList()">getList</el-button>
<el-button @click="clearStorage()">clear Local Storage</el-button>
<div v-for="(item) in list" :key="item.aid">{{ item }}</div>
</div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
name: "demo",
data() {
return {
lit: [],
};
},
components: {},
computed: {
...mapState(["list"]),
},
methods: {
...mapMutations(["setList", "addItem", "updateItem", "deleteItem"]),
clearStorage() {
// localStorage.setItem("list", []);
localStorage.removeItem('list');
},
getList() {
console.log(this.list.length);
let that = this;
this.axiOS
.get('/abc/onetooneAnnote')
.then((response) => {
//返回结果
let lt = response.data;
this.setStore(lt);
})
.catch((error) => {
console.log(error)
})
},
setStore(lt) {
let that = this;
if (that.list.length == 0) {
//初始化
this.setList(lt);
} else {
let lit = that.list;
lt.forEach((newItem, i) => {
const index = lit.findIndex((litem) => litem.aid === newItem.aid);
if (index == -1) {
// 添加
this.addItem(newItem);
} else {
const oldItem = lit[index];
if (JSON.stringify(oldItem) != jsON.stringify(newItem)) {
// 更新
let payload = {
data: newItem,
index: index,
}
this.updateItem(payload);
}
}
})
//删除
this.deleteItem(lt);
}
},
},
mounted() {
},
created() {},
destroyed() {},
watch: {},
}
</script>
<style scoped>
</style>
<style></style>
不刷新页面,使用的vuex内的值,刷新页面才会重新从localstorage中获取
subscribe
监听指定的mutation
方法,对应方法调用则更新localstorage
setItemWithExpiry
,将时间作为变量和数据整编成一个对象,存入localStorage
,在subscribe
时调用此函数import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
// 将数据存储到LocalStorage并设置过期时间(毫秒)
function setItemWithExpiry(key, value, ttl) {
const item = {
value: value,
expiry: new Date().getTime() + ttl,
};
localStorage.setItem(key, JSON.stringify(item));
}
const store = new Vuex.Store({
state: {
list: JSON.parse(localStorage.getItem("list")).value || [],
},
getters: {},
mutations: {
setList(state, list) {
state.list = list;
},
addItem(state, item) {
state.list.push(item);
},
updateItem(state, payload) {
Vue.set(state.list, payload.index, payload.data);
},
deleteItem(state, lt) {
let newIds = lt.map((item) => item.aid);
state.list = state.list.filter((item) => newIds.includes(item.aid));
},
},
actions: {}
})
// 监听订阅
store.subscribe((mutation, state) => {
if (['setList', 'addItem', 'updateItem', 'deleteItem'].includes(mutation.type)) {
// 不设置定时删除
// localStorage.setItem('list', JSON.stringify(state.list));
// 使用定时删除
setItemWithExpiry("list", state.list, 10 * 1000);
}
});
export default store;
其中获取vuex的值,如果每次都想直接从localstorage中读取,可以使用store的getters属性
getters: {
getList: (state) => {
return state.list;
},
},
组件中使用
<div v-for="(item) in getList" :key="item.aid">{{ item }}</div>
import { mapGetters } from "vuex";
computed: {
...mapGetters(['getList']),
},
官方GitHub地址:https://github.com/xxwwp/StorageTiming/blob/main/docs/zh.md
App.vue
中全局设置checkExpiry
可以遍历全部localstorage
,也可以只关注某几个变量<template>
...
</template>
<script>
export default {
data() {
return {
timer: "",
}
},
components: {},
methods: {
getItemWithExpiry(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) {
return null;
}
const item = JSON.parse(itemStr);
const currentTime = new Date().getTime();
if (currentTime > item.expiry) {
// 如果数据已经过期,删除它
localStorage.removeItem(key);
return null;
}
return item.value;
},
// 检查LocalStorage中的数据是否过期
checkExpiry() {
this.getItemWithExpiry("list");
// for (let i = 0; i < localStorage.length; i++) {
// const key = localStorage.key(i);
// getItemWithExpiry(key);
// }
},
startCheck(){
let that = this;
this.timer = setInterval(() => { //开启定时器
console.log("check localstorage");
that.checkExpiry()
}, 1000)
}
},
mounted() {
this.startCheck();
},
beforeDestroy(){
clearInterval(this.timer)//组件销毁之前清掉timer
},
computed: {},
created() {
},
}
</script>
<style scoped></style>
<style></style>
初始化
新增
更新和删除
谷歌浏览器查看localstorage(F12 --> Application -->Storage)
localstorage定时删除
到此这篇关于vuex存储数组(新建,增,删,更新),并存入localstorage定时删除的文章就介绍到这了,更多相关vuex存储数组内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: vuex存储数组(新建,增,删,更新)并存入localstorage定时删除功能实现
本文链接: https://www.lsjlt.com/news/211995.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0