Article directory
Prepare
Create a store folder in the root directory and create index.js internally
1. Plug-in implementation
Address: vuex-persistedstate-npm
1.Install the plug-in
The code is as follows (example):
npm install --save vuex-persistedstate
2. index.js configuration:
import api from '@/static/api/index.js' // 引入接口
import createPersistedState from 'vuex-persistedstate' // 引入数据持久化插件
import Vue from 'vue' // 导入vue包
import Vuex from 'vuex' // 导入vuex包
Vue.use(Vuex); // vue的插件机制使用vuex
// 创建Vuex:构造函数创建store常量
const store = new Vuex.Store({
// state:提供唯一的公共数据源,所有共享的数据都要统一放到store中的state存储
state: {
// 持久化常用参数
token: uni.getStorageSync('vuex').token, // token
userId: uni.getStorageSync('vuex').userId, // 用户id
},
// mutations 同步变更state数据,传多个参数需要用对象的方式
mutations: {
// 保存TOKEN
SET_TOKEN: (state, token) => {
state.token = token
},
// 保存用户ID
SET_ID: (state, id) => {
state.userId = id
},
// 定义全局的清理方法
RESET_ALL_STATE(state) {
state.token = '';
state.userId = '';
},
},
// actions 异步变更state数据
actions: {
// 登陆,持久化存储token,id
loginApi(context, data) {
return new Promise((resolve, reject) => {
api.userLogin(data).then(res => {
const {
token,
user_id,
} = res.data
context.commit('SET_ID', id)
context.commit('SET_TOKEN', token)
}).catch(err => {
reject(err)
})
})
},
// 退出登陆清空state
logout(context) {
return new Promise((resolve, reject) => {
context.commit('RESET_ALL_STATE')
})
}
},
// getters 用于对store中的已有数据进行加工处理形成新的数据,如果store中的数据发生变化,
getters: {},
// plugins 插件配置
plugins: [
createPersistedState({
paths: ['token', 'userId'],
storage: { // 存储方式定义
getItem: (key) => uni.getStorageSync(key), // 获取
setItem: (key, value) => uni.setStorageSync(key, value), // 存储
removeItem: (key) => uni.removeStorageSync(key) // 删除
}
})
]
})
export default store
Plug-in API description:
- key: key to store persistent state (default vuex)
- reduce: key to store persistent state (default vuex)
- paths : An array of any paths to partial persistent state. If no path is given, the complete state is persisted. (default:[])
- reducer: A function that will be called to persist the state based on the given path. These values are included by default.
- subscriber: A function called to set up a mutation subscription. The default is store => handler => store.subscribe(handler)
- storage: instead of (or with) getState and setState. Default is localStorage.
- getState : Function that will be called to rehydrate the previous persistent state. Storage is used by default.
- setState: Function that will be called to maintain the given state. Storage is used by default.
- filter : Function that will be called to filter any mutations that will eventually trigger setState on the store. Default is () => true
3. Get persistent data (such as login page) :
login() {
this.$store.dispatch('loginApi', data).then(res => {
uni.reLaunch({
url: '/pages/index/index'
});
})
}
4. Use state (such as personal homepage):
<template>
<view>
<text>{
{id}}</text>
</view>
</template>
<script>
import {mapState} from 'vuex'
export default {
data() {
return {}
},
computed: {
...mapState(["id"),
},
}
</script>
2. Local storage implementation
The code is as follows (example):
import api from '@/static/api/index.js' // 引入接口
import createPersistedState from 'vuex-persistedstate' // 引入数据持久化插件
import Vue from 'vue' // 导入vue包
import Vuex from 'vuex' // 导入vuex包
Vue.use(Vuex); // vue的插件机制使用vuex
const store = new Vuex.Store({
// state:提供唯一的公共数据源,所有共享的数据都要统一放到store中的state存储
state: {
// 持久化
test: uni.getStorageSync('test'),
},
// mutations 同步变更state数据,传多个参数需要用对象的方式
mutations: {
// 也可以用 JSON.parse(JSON.stringify(test))
SET_TEST: (state, test) => {
state.test = test
uni.setStorageSync('test', state.test)
}
},
// actions 异步变更state数据
actions: {
// 持久化实现
getTest(context, test) {
context.commit('SET_TEST', test)
}
},
// getters 用于对store中的已有数据进行加工处理形成新的数据,如果store中的数据发生变化,
getters: {}
})
export default store
Summarize
This article only briefly introduces the use of vuex persistence, plug-in or local cache.