Vue(四):vuex持久化存储插件 – vuex-persist、vuex-persistedstate

vuex插件

官网: https://vuex.vuejs.org/zh/guide/plugins.htmlmutations

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- @/views/Login.vue -->
<template>
  <div class="login">
    {<!-- -->{$store.state.data.name}}
  </div>
</template>

<script>
export default {<!-- -->
  name: 'Login',
  created(){<!-- --> // 定义vuex中state数据
    this.$store.commit("saveData", {<!-- -->name: 'Lee'});
  }
}
</script>

<!-- @/views/Home.vue -->
<template>
  <div class="home">
    {<!-- -->{$store.state.data.name}}
  </div>
</template>

1.vuex-persist

npm i vuex-persist

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// @/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersistence from 'vuex-persist'

Vue.use(Vuex)

export default new Vuex.Store({<!-- -->
  state: {<!-- -->
    data: {<!-- -->}
  },
  mutations: {<!-- -->
    saveData(state, obj){<!-- -->
      state.data = obj;
    }
  },
  plugins: [new VuexPersistence().plugin]
})

2.vuex-persistedstate

npm i vuex-persistedstate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// @/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({<!-- -->
  state: {<!-- -->
    data: {<!-- -->}
  },
  mutations: {<!-- -->
    saveData(state, obj){<!-- -->
      state.data = obj;
    }
  },
  plugins: [createPersistedState()]
})

解释

以上两个插件默认存储的位置都是localStorage,需要特殊配置的话可以参考插件github网址

  • vuex-persist:
    • https://github.com/championswimmer/vuex-persist
  • vuex-persistedstate:
    • https://github.com/robinvdvleuten/vuex-persistedstate