vuex缓存插件
在线地址:codesandbox.io/p/sandbox/v…
uni-app使用示例
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
vuex getter的使用
actions使用
mapState使用
// data是模块名字
mapGetters
computed: {
...mapGetters([
'sidebar',
'avatar',
'name'
])
},