vuex存储数组(新建,增,删,更新),并存入localstorage定时删除

18 篇文章 1 订阅

vuex存储数组(新建,增,删,更新),并存入localstorage定时删除

使用背景

初始化一个完整数组,但在业务逻辑中会单独更新或增删其中的一部分或全部。

如果每次都是全部更新,直接使用set替换即可,但大部分数组不变只修改个别数据,直接替换的代价较大,因此维护一个增删改的业务。

原来的数据都是有意义的,新数据可能是初始化的,不能直接替换成新数据,新数据可能只是增删了id,但是其他数据内容还要继续使用旧数据的,所以只能在旧数据基础上进行维护

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" }
]

组件中判断

  1. 新建的时候进行判断that.list.length == 0 || that.list == null,直接set赋值即可
  2. 如果不为0,说明已经初始化并赋值,遍历当前数组(本文中数据来自后端)
    • id不存在(旧数组没有而新数组有),则调用add添加
    • id存在需要判断这个对象是否完全相同,不完全相同则调用update
  3. 最后调用delete,store中直接使用filter过滤掉新数组中有而旧数组没有的对象(delete的逻辑可以单独存在,不与更新一起)

自行修改使用:大更新需要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>

存入localstorage并设置定时删除

不刷新页面,使用的vuex内的值,刷新页面才会重新从localstorage中获取

自定义实现
  1. 使用subscribe监听指定的mutation方法,对应方法调用则更新localstorage
  2. 实现函数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']),
  },
使用storage-timing插件

官方github地址:https://github.com/xxwwp/StorageTiming/blob/main/docs/zh.md

调用定时删除

  1. 设置定时器,可以在App.vue中全局设置
  2. 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定时删除
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

anjushi_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值