最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vuex存儲數(shù)組(新建,增,刪,更新)并存入localstorage定時刪除功能實現(xiàn)

 更新時間:2023年04月29日 10:07:20   作者:anjushi_  
這篇文章主要介紹了vuex存儲數(shù)組(新建,增,刪,更新),并存入localstorage定時刪除,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

vuex存儲數(shù)組(新建,增,刪,更新),并存入localstorage定時刪除

使用背景

初始化一個完整數(shù)組,但在業(yè)務(wù)邏輯中會單獨更新或增刪其中的一部分或全部。

如果每次都是全部更新,直接使用set替換即可,但大部分?jǐn)?shù)組不變只修改個別數(shù)據(jù),直接替換的代價較大,因此維護(hù)一個增刪改的業(yè)務(wù)。

原來的數(shù)據(jù)都是有意義的,新數(shù)據(jù)可能是初始化的,不能直接替換成新數(shù)據(jù),新數(shù)據(jù)可能只是增刪了id,但是其他數(shù)據(jù)內(nèi)容還要繼續(xù)使用舊數(shù)據(jù)的,所以只能在舊數(shù)據(jù)基礎(chǔ)上進(jìn)行維護(hù)

store中實現(xiàn)增刪改

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;

組件中維護(hù)數(shù)組,進(jìn)行判斷

對象數(shù)組數(shù)據(jù)格式

[
  { "aid": "1", "aname": "111", "tobid": "1" }
  { "aid": "2", "aname": "ddd", "tobid": "2" }
]

組件中判斷

  • 新建的時候進(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存在需要判斷這個對象是否完全相同,不完全相同則調(diào)用update
  • 最后調(diào)用delete,store中直接使用filter過濾掉新數(shù)組中有而舊數(shù)組沒有的對象(delete的邏輯可以單獨存在,不與更新一起)

自行修改使用:大更新需要add和delete,局部更新只有update

例如舊數(shù)組是【1,2】,新數(shù)組是【2,3】,經(jīng)過第二步之后,舊數(shù)據(jù)變?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) => {
          //返回結(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>

存入localstorage并設(shè)置定時刪除

不刷新頁面,使用的vuex內(nèi)的值,刷新頁面才會重新從localstorage中獲取

自定義實現(xiàn)

  • 使用subscribe監(jiān)聽指定的mutation方法,對應(yīng)方法調(diào)用則更新localstorage
  • 實現(xiàn)函數(shù)setItemWithExpiry,將時間作為變量和數(shù)據(jù)整編成一個對象,存入localStorage,在subscribe時調(diào)用此函數(shù)
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
// 將數(shù)據(jù)存儲到LocalStorage并設(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è)置定時刪除
    // 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

調(diào)用定時刪除

  • 設(shè)置定時器,可以在App.vue中全局設(shè)置
  • checkExpiry可以遍歷全部localstorage,也可以只關(guān)注某幾個變量
<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;
    },
    // 檢查LocalStorage中的數(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(() => { //開啟定時器
        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定時刪除

到此這篇關(guān)于vuex存儲數(shù)組(新建,增,刪,更新),并存入localstorage定時刪除的文章就介紹到這了,更多相關(guān)vuex存儲數(shù)組內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于Vue實現(xiàn)簡單的權(quán)限控制

    基于Vue實現(xiàn)簡單的權(quán)限控制

    這篇文章主要為大家學(xué)習(xí)介紹了如何基于Vue實現(xiàn)簡單的權(quán)限控制,文中的示例代碼講解詳細(xì),具有一定的參考價值,需要的小伙伴可以了解一下
    2023-07-07
  • Vue前端解析Excel數(shù)據(jù)方式

    Vue前端解析Excel數(shù)據(jù)方式

    這篇文章主要介紹了Vue前端解析Excel數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • vue3 element-plus el-tree自定義圖標(biāo)方式

    vue3 element-plus el-tree自定義圖標(biāo)方式

    這篇文章主要介紹了vue3 element-plus el-tree自定義圖標(biāo)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • Vue中import與@import的區(qū)別及使用場景說明

    Vue中import與@import的區(qū)別及使用場景說明

    這篇文章主要介紹了Vue中import與@import的區(qū)別及使用場景說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Vue+Element的后臺管理框架的整合實踐

    Vue+Element的后臺管理框架的整合實踐

    本文主要介紹了Vue+Element的后臺管理框架,在框架上,領(lǐng)導(dǎo)要用AdminLTE這套模板,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • vue解決子組件樣式覆蓋問題scoped deep

    vue解決子組件樣式覆蓋問題scoped deep

    文章主要介紹了在Vue項目中處理全局樣式和局部樣式的方法,包括使用scoped屬性和深度選擇器(/deep/)來覆蓋子組件的樣式,作者建議所有組件必須使用scoped,以避免樣式?jīng)_突,對于父組件覆蓋子組件的樣式,作者推薦給子組件指定自定義類名
    2025-01-01
  • vant/vue跨域請求解決方案

    vant/vue跨域請求解決方案

    這篇文章主要介紹了vant/vue跨域請求解決方案,需要的朋友可以參考下
    2022-12-12
  • 詳解Vue中的keep-alive

    詳解Vue中的keep-alive

    這篇文章主要為大家介紹了Vue中的keep-alive,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • 淺談vue.js導(dǎo)入css庫(elementUi)的方法

    淺談vue.js導(dǎo)入css庫(elementUi)的方法

    下面小編就為大家分享一篇淺談vue.js導(dǎo)入css庫(elementUi)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • vue-calendar-component日歷組件報錯Clock is not defined解決

    vue-calendar-component日歷組件報錯Clock is not defi

    這篇文章主要為大家介紹了vue-calendar-component日歷組件報錯Clock is not defined解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11

最新評論

怀远县| 麦盖提县| 横山县| 康马县| 北碚区| 夏河县| 化隆| 隆回县| 合江县| 鄂托克旗| 东乡县| 枣强县| 达州市| 太白县| 遂溪县| 东丰县| 上林县| 明星| 调兵山市| 宁安市| 亚东县| 郑州市| 栾川县| 古丈县| 临清市| 称多县| 库车县| 弋阳县| 鄄城县| 江山市| 普安县| 凤凰县| 汾西县| 德格县| 山东省| 泸水县| 北辰区| 顺平县| 博湖县| 娱乐| 巨鹿县|