vuex存儲數組(新建,增,刪,更新)并存入localstorage定時刪除功能實現
vuex存儲數組(新建,增,刪,更新),并存入localstorage定時刪除
使用背景
初始化一個完整數組,但在業(yè)務邏輯中會單獨更新或增刪其中的一部分或全部。
如果每次都是全部更新,直接使用set替換即可,但大部分數組不變只修改個別數據,直接替換的代價較大,因此維護一個增刪改的業(yè)務。
原來的數據都是有意義的,新數據可能是初始化的,不能直接替換成新數據,新數據可能只是增刪了id,但是其他數據內容還要繼續(xù)使用舊數據的,所以只能在舊數據基礎上進行維護
store中實現增刪改
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" } ]
組件中判斷
- 新建的時候進行判斷that.list.length == 0 || that.list == null,直接set賦值即可
- 如果不為0,說明已經初始化并賦值,遍歷當前數組(本文中數據來自后端)
- id不存在(舊數組沒有而新數組有),則調用add添加
- id存在需要判斷這個對象是否完全相同,不完全相同則調用update
- 最后調用delete,store中直接使用filter過濾掉新數組中有而舊數組沒有的對象(delete的邏輯可以單獨存在,不與更新一起)
自行修改使用:大更新需要add和delete,局部更新只有update
例如舊數組是【1,2】,新數組是【2,3】,經過第二步之后,舊數據變?yōu)椤?,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>
存入localstorage并設置定時刪除
不刷新頁面,使用的vuex內的值,刷新頁面才會重新從localstorage中獲取
自定義實現
- 使用
subscribe
監(jiān)聽指定的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: {} }) // 監(jiān)聽訂閱 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']), },
使用storage-timing插件
官方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存儲數組內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在vue項目中promise解決回調地獄和并發(fā)請求的問題
這篇文章主要介紹了在vue項目中promise解決回調地獄和并發(fā)請求的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue3中Element Plus Table(表格)點擊獲取對應id方式
這篇文章主要介紹了Vue3中Element Plus Table(表格)點擊獲取對應id方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10詳解element-ui動態(tài)限定的日期范圍選擇器代碼片段
這篇文章主要介紹了element-ui動態(tài)限定的日期范圍選擇器代碼片段,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07vue-router next(false) 禁止訪問某個頁面時,不保留歷史訪問記錄問題
這篇文章主要介紹了vue-router next(false) 禁止訪問某個頁面時,不保留歷史訪問記錄問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11