【Vue】缓存数据的方式归纳

缓存方式

  1. localStorage
  2. sessionStorage
  3. storage.js(实际上时多种方式的集合也包括了前两种)
  4. vuex
  5. keep-alive(主要用于保留组件状态或避免重新渲染,自动缓存,并不能自己读写)

localStorage

可长期存储数据,除非用户清楚localStorage信息,否则数据会一直存在。同一中浏览器之间,不同页面,数据可以共享。

//存
// 将this.pickerItem的数据存储入insuranceCode,需提前转化成string类型
localStorage.setItem("insuranceCode", JSON.stringify(this.pickerItem));
//取
JSON.parse(localStorage.getItem("insuranceCode"));
//清除某一项
localStorage.removeItem("insuranceCode");
//清除所有
localStorage.clear();

sessionStorage

短期存储数据,用户关闭标签页后或直接关闭浏览器后数据会清空。同一浏览器不同页面之间,数据不可共享

//存
sessionStorage.setItem("insuranceCode", JSON.stringify(this.pickerItem));
//取
JSON.parse(sessionStorage.getItem("insuranceCode"));
//清除某一项
sessionStorage.removeItem("insuranceCode");
//清除所有
sessionStorage.clear();

vuex

1.创建vuex
首先我们要新建一个store文件夹,下面包含index.js,项目过大可再加一个modules文件夹下面写js,这里就在modules文件夹里面新建一个proudct.js文件。
在这里插入图片描述
我们需要写一个vuex,相当于我要放苹果,所以我需要先买一个果盘。
这里我命名为proudct,代码如下:

import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const state = {
    
    
 id:null,
 code:null,

}
const mutations = {
    
    
  //保存数据
  CHANGE_ACTIVE_LI(state, {
     
      id, code }) {
    
    
    state.id = id
    state.code = code
  },
   //清除数据
   SET_CLEAR_DATA(state,data){
    
    
    state.id=data
  }
}
const actions = {
    
    
  //保存数据
  changeSetting({
     
      commit }, data) {
    
    
    commit('CHANGE_ACTIVE_LI', {
    
     id: data.id, code: data.code })
  },
  //清除数据
  clearVuex({
     
      commit }) {
    
    
    commit("SET_CLEAR_DATA", null);
  },

}
export default {
    
    
  //解决模块名冲突
  namespaced: true,
  state,
  mutations,
  actions


然后记住在store下面的index.js里面引入,这一步非常重要:
在这里插入图片描述

2.存入数据

 next() {
    
    
 //这里的product/changeSetting是指定vuex中的方法,我这里指定把后面的对象加在prouduct中changeSetting方法里面去
      this.$store.dispatch("product/changeSetting", {
    
    
        id: this.id,
        code: this.code,
      });
    },

3.取出数据

//取出vuex中proudct.js中的id的值
  this.id = this.$store.state.product.id;

到这里,已经看出来这种方法的不足之处,如果我要放很多数据,那我岂不是要写很多键值,而且取值的时候也要写很多个this.$store.state.product.id;
所以,为了解决这一问题,我们可以使用辅助函数,可以存放对象的方式。

storage.js

import storage from 'store'
// Store current user
store.set('user', {
    
     name:'Marcus' })
// Get current user
store.get('user')
// Remove current user
store.remove('user')
// Clear all keys
store.clearAll()
// Loop over all stored values
store.each(function(value, key) {
    
    
    console.log(key, '==', value)
})

测试得出,默认存储在localStorage中

store.js包含了各种存储的解决方案,比如在某些localStorage失效的场景中,可以使用cookieStorage.js。掌握它,基本可以一网打尽缓存解决方案。

  • all.js All the storages in one handy place.
  • localStorage.js Store values in localStorage. Great for all modern
    browsers.
  • sessionStorage.js Store values in sessionStorage.
  • cookieStorage.js Store values in cookies. Useful for Safari Private
    mode.
  • memoryStorage.js Store values in memory. Great fallback to ensure
    store functionality at all times.
  • oldFF-globalStorage.js Store values in globalStorage. Only useful for
    legacy Firefox 3+.
  • oldIE-userDataStorage.js Store values in userData. Only useful for
    legacy IE 6+.

keep-alive

Props:

  • include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
  • exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
  • max - 数字。最多可以缓存多少组件实例。

用法:

包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 相似, 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。

当组件在 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

在 2.2.0 及其更高版本中,activated 和 deactivated 将会在 树内的所有嵌套组件中触发。

<!-- 基本 -->
<keep-alive>
  <component :is="view"></component>
</keep-alive>

<!-- 多个条件判断的子组件 -->
<keep-alive>
  <comp-a v-if="a > 1"></comp-a>
  <comp-b v-else></comp-b>
</keep-alive>

<!--`<transition>` 一起使用 -->
<transition>
  <keep-alive>
    <component :is="view"></component>
  </keep-alive>
</transition>

注意, 是用在其一个直属的子组件被开关的情形。如果你在其中有 v-for 则不会工作。如果有上述的多个条件性的子元素, 要求同时只有一个子元素被渲染。

include and exclude

include 和 exclude prop 允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示:

<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

max

最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

不会在函数式组件中正常工作,因为它们没有缓存实例。

参考

Vue.Js 组件keep-alive
vue存储数据的几种方法(Vuex与本地存储)
vue的缓存有几种实现方式

猜你喜欢

转载自blog.csdn.net/weixin_44231544/article/details/125254598