Keep your vuex state between page reloads.

Overview

vuex-persisted-states

Keep your vuex states between page reloads.

在页面重新加载之间保持您的 vuex 状态

原理: 借助缓存机制来存储 vuex 状态

安装(Install)

npm install vuex-persisted-states -D

yarn add vuex-persisted-states -D

使用(Usage)

基础用法

vuexindex 文件中引入

默认将所有的 state 存储到 window.localStorage

import Vuex from 'vuex';
import vuexPersistedStates from 'vuex-persisted-states';

const store = new Vuex.Store({
  // ...
  plugins: [vuexPersistedStates()],
});

参数配置(options)

  • key

    key 缓存的标志,来修改或获取缓存的值

    默认缓存的 key 为 vuex

    // ...
    const store = new Vuex.Store({
      // ...
      plugins: [
        vuexPersistedStates({
          // 修改 key 为 storage
          key: 'storage',
        }),
      ],
    });
  • storage

    缓存的机制

    localStorage 、sessionStorage、js-cookie、cookie...

    // ...
    const store = new Vuex.Store({
      // ...
      plugins: [
        vuexPersistedStates({
          // 修改存储的位置
          storage: window.sessionStorage,
        }),
      ],
    });
  • paths

    缓存状态的集合

    // ...
    const store = new Vuex.Store({
      state: {
        a: 1,
        b: {
          c: 2,
          d: 3,
        },
      },
      // ...
      plugins: [
        vuexPersistedStates({
          // 缓存 a 和 b.c 的状态
          paths: ['a', 'b.c'],
        }),
      ],
    });
  • spreadPaths

    paths 的集合默认是缓存到 storage 中

    spreadPaths 可以将不同的状态属性缓存的位置不一样

    // ...
    const store = new Vuex.Store({
      state: {
        a: 1,
        b: {
          c: 2,
          d: 3,
        },
      },
      // ...
      plugins: [
        vuexPersistedStates({
          // 缓存 a 到 window.sessionStorage
          // 缓存 b 到 window.localStorage
          spreadPaths: [
            {
              storage: window.sessionStorage,
              // 修改不同 storage 的 key
              key: 'session',
              paths: ['a'],
            },
            {
              paths: ['b'],
            },
          ],
        }),
      ],
    });
  • resetMutationType

    触发还原 state 状态的 mutation 方法

    默认声明一个 resetStates方法的 mutation 方法

    // ...
    const store = new Vuex.Store({
      state: {
        a: 1,
        b: {
          c: 2,
          d: 3,
        },
      },
      mutations: {
        resetStates(state, params) {
          return;
        },
        // cleanStates(state, params){
        //   return;
        // }
      },
      // ...
      plugins: [
        vuexPersistedStates({
          // 修改重置 states 的 mutations 的方法
          // resetMutationType: "cleanStates"
        }),
      ],
    });
    
    // 在组件内调用
    // params 不传值则还原所有的state的状态
    // params = ["a"]  接受 string[] 来还原指定的 state 状态
    this.$store.commit('resetStates');
    // this.$store.commit("cleanStates")
    // this.$store.commit("resetStates",["a"])
    // this.$store.commit("cleanStates",["a"])
  • filterMutation

    过滤那些 mutation 方法不需要进行缓存操作 ,减少不必要的代码运行

    // ...
    const store = new Vuex.Store({
      state: {
        a: 1,
        b: {
          c: 2,
          d: 3,
        },
      },
      // ...
      plugins: [
        vuexPersistedStates({
          filterMutation: (mutation) => {
            // 根据mutation type 过滤掉 cleanStates 方法
            if (mutation.type !== 'resetStates') {
              return true;
            }
            return false;
          },
        }),
      ],
    });
  • 对状态值存储做安全处理

    对值进行加密存储

    // ...
    import { Base64 } from 'js-base64';
    
    const store = new Vuex.Store({
      // ...
      plugins: [
        vuexPersistedState({
          setState(value) {
            // 存加密
            return Base64.encode(JSON.stringify(value));
          },
          getState(value) {
            // 取解密
            return JSON.parse(Base64.decode(value));
          },
        }),
      ],
    });

Attribute

属性 类型 默认值
key string vuex
storage Storage localStorage
paths string[] -
spreadPaths Path[] -
resetMutationType string resetStates
filterMutation (mutation:Store)=>boolean true
setState (value:any)=>string -
getState (value:string)=>any -

Path[]

属性 类型 默认值
storage? Storage localStorage
key? string vuex
paths string[] -
You might also like...
A project to demonstrate the use of Store and state, getters, mutations in Vuex and VueJS

Vuex State Sample 🎁 🎯 A project to demonstrate the use of Store and state, getters, mutations in Vuex and VueJS. Create Vuex Store and use it to hol

Lightweight vuex inspired centralized state management library for all kinds of javascript applications. Great for React Native.

Verx Lightweight vuex inspired centralized state management library for all kinds of javascript applications. install npm install --save verx # yarn a

🏖 A concise & flexible state model for Redux/MobX/Vuex, etc.

USM USM is a universal state modular library, supports Redux(4.x), MobX(6.x), Vuex(4.x) and Angular(2.0+). Support Libraries/Frameworks None Redux Mob

Helper functions to ease working with Vuex, Centralized State Management for Vue.js.

vuex-helpers Helper functions to ease working with Vuex, Centralized State Management for Vue.js. Development The following examples use docker and do

Type safe state management inspired by Vuex

Sinai Type safe state management inspired by Vuex. This library includes many type level hacks. Use at your own risk and do not use if you are unsure

⛓ Vuex State Storage Sync
⛓ Vuex State Storage Sync

Vuex State and Storage(local, session) Synchronization module 🕹 Guide Install $ npm install --save vuex-state-storage-sync Usage import Vue from 'vue

Flexible binding between Vue and Redux

vuejs-redux Description Flexible binding between Vue and Redux, allowing use of multiple stores. It works, in the same way, like render props does in

DruxtJS; A bridge between frameworks.

DruxtJS; A bridge between frameworks. Druxt = DRUpal + nUXT = Fully Decoupled Drupal. Links Documentation: https://druxtjs.org Community Discord serve

vuex-module-generator - It allows you to create a vuex module easily.

Vuex Module Generator (VMG) VMG allows you to create a vuex module easily. See All implementations. See Customer Example. Supported module types Clone

Owner
Chengbotao
拒绝标签,追求自我 一切尽意,百事从欢!
Chengbotao
Vuex state synchronization between iframe/window

vuex-iframe-sync English | 中文 Vuex state synchronization between iframe/window Your star is the greatest encouragement to me. ✨ Features: support ifra

Jiahui.Liang 101 Dec 17, 2022
💾🔗🖥️ Share, synchronize and persist state between multiple tabs with this plugin for Vuex. TypeScript types included.

vuex-multi-tab-state This Vuex plugin allows you to sync and share the status of your Vue application across multiple tabs or windows using the local

Gabriel Martín Blázquez 155 Nov 19, 2022
Vuex state persistance and synchronization between tabs/windows.

vuex-basement Vuex state persistance and synchronization between tabs/windows. Tested to work with Vue2. One Shortcomming (please read before use). Th

Rashad Saleh 65 Jun 29, 2022
Share vuex mutations between tabs/windows

vuex-shared-mutations Share certain Vuex mutations across multiple tabs/windows. Basic example Nuxt example Installation $ npm install vuex-shared-mut

Illya Klymov 566 Dec 12, 2022
Easily share reactive data between your Vue components.

vue-stash A Vue.js plugin that makes it easy to share reactive data between components. This plugin is best suited for the rapid development of protot

Cody Mercer 406 Dec 10, 2022
📦 Fast, Simple, and Lightweight State Manager for Vue 3.0 built with composition API, inspired by Vuex.

v-bucket NPM STATUS: ?? Fast, Simple, and Lightweight State Management for Vue 3.0 built with composition API, inspired by Vuex. Table of Contents Mai

mehdi 42 Aug 10, 2022
Local state management within Vuex

vuex-local Local state management within Vuex Why? Global state management is one of the problems on huge application development. Developers address

Katashin 64 Nov 11, 2022
Simplify vuex loading state management

vuex-loading Simplify vuex loading state management Installing Using npm: $ npm install vuex-loadings -s Know Simplify vuex loading state management n

zhoulin 3 Jul 30, 2020
A vue boiler plate with state management, vuex, vue-router that can be backed by a laravel restful api using jwt auth

Laravel 6 (LTS) Vue.js Frontend Boilerplate A Vue.js Frontend starter project kit template/boilerplate with Laravel 6 Backend API support. Features Re

MUWONGE HASSAN 2 Oct 12, 2021
Simple counter with Vue.js and Vuex as state management

vuex-counter Project setup npm install Compiles and hot-reloads for development npm run serve Compiles and minifies for production npm run build Li

Kevin Hamdajani 0 Dec 30, 2021