您好,登錄后才能下訂單哦!
這篇文章主要介紹“vuex怎么實(shí)現(xiàn)存儲(chǔ)數(shù)組并存入localstorage定時(shí)刪除功能”,在日常操作中,相信很多人在vuex怎么實(shí)現(xiàn)存儲(chǔ)數(shù)組并存入localstorage定時(shí)刪除功能問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”vuex怎么實(shí)現(xiàn)存儲(chǔ)數(shù)組并存入localstorage定時(shí)刪除功能”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
初始化一個(gè)完整數(shù)組,但在業(yè)務(wù)邏輯中會(huì)單獨(dú)更新或增刪其中的一部分或全部。
如果每次都是全部更新,直接使用set替換即可,但大部分?jǐn)?shù)組不變只修改個(gè)別數(shù)據(jù),直接替換的代價(jià)較大,因此維護(hù)一個(gè)增刪改的業(yè)務(wù)。
原來的數(shù)據(jù)都是有意義的,新數(shù)據(jù)可能是初始化的,不能直接替換成新數(shù)據(jù),新數(shù)據(jù)可能只是增刪了id,但是其他數(shù)據(jù)內(nèi)容還要繼續(xù)使用舊數(shù)據(jù)的,所以只能在舊數(shù)據(jù)基礎(chǔ)上進(jìn)行維護(hù)
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;
對(duì)象數(shù)組數(shù)據(jù)格式
[ { "aid": "1", "aname": "111", "tobid": "1" } { "aid": "2", "aname": "ddd", "tobid": "2" } ]
組件中判斷
新建的時(shí)候進(jìn)行判斷that.list.length == 0 || that.list == null,直接set賦值即可
如果不為0,說明已經(jīng)初始化并賦值,遍歷當(dāng)前數(shù)組(本文中數(shù)據(jù)來自后端)
id不存在(舊數(shù)組沒有而新數(shù)組有),則調(diào)用add添加
id存在需要判斷這個(gè)對(duì)象是否完全相同,不完全相同則調(diào)用update
最后調(diào)用delete,store中直接使用filter過濾掉新數(shù)組中有而舊數(shù)組沒有的對(duì)象(delete的邏輯可以單獨(dú)存在,不與更新一起)
自行修改使用:大更新需要add和delete,局部更新只有update
例如舊數(shù)組是【1,2】,新數(shù)組是【2,3】,經(jīng)過第二步之后,舊數(shù)據(jù)變?yōu)椤?,2,3】,但【1】是需要?jiǎng)h除的
<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) => { //返回結(jié)果 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>
不刷新頁(yè)面,使用的vuex內(nèi)的值,刷新頁(yè)面才會(huì)重新從localstorage中獲取
使用subscribe
監(jiān)聽指定的mutation
方法,對(duì)應(yīng)方法調(diào)用則更新localstorage
實(shí)現(xiàn)函數(shù)setItemWithExpiry
,將時(shí)間作為變量和數(shù)據(jù)整編成一個(gè)對(duì)象,存入localStorage
,在subscribe
時(shí)調(diào)用此函數(shù)
import Vue from "vue" import Vuex from "vuex" Vue.use(Vuex) // 將數(shù)據(jù)存儲(chǔ)到LocalStorage并設(shè)置過期時(shí)間(毫秒) 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)) { // 不設(shè)置定時(shí)刪除 // localStorage.setItem('list', JSON.stringify(state.list)); // 使用定時(shí)刪除 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']), },
設(shè)置定時(shí)器,可以在App.vue
中全局設(shè)置
checkExpiry
可以遍歷全部localstorage
,也可以只關(guān)注某幾個(gè)變量
<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) { // 如果數(shù)據(jù)已經(jīng)過期,刪除它 localStorage.removeItem(key); return null; } return item.value; }, // 檢查L(zhǎng)ocalStorage中的數(shù)據(jù)是否過期 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(() => { //開啟定時(shí)器 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定時(shí)刪除
到此,關(guān)于“vuex怎么實(shí)現(xiàn)存儲(chǔ)數(shù)組并存入localstorage定時(shí)刪除功能”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。