uniapp中使用vuex并持久化

文章目录


准备

根目录下创建store文件夹,内部创建index.js


一、插件实现

地址:vuex-persistedstate - npm

1.安装插件

代码如下(示例):

npm install --save vuex-persistedstate

 2.index.js配置:

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

插件的api说明:

  • key: 存储持久状态的key(默认vuex)
  • reduce: 存储持久状态的key(默认vuex)
  • paths :部分持续状态的任何路径的数组。如果没有路径给出,完整的状态是持久的。(默认:[])
  • reducer :一个函数,将被调用来基于给定的路径持久化的状态。默认包含这些值。
  • subscriber :一个被调用来设置突变订阅的函数。默认为store => handler => store.subscribe(handler)
  • storage :而不是(或与)getState和setState。默认为localStorage。
  • getState :将被调用以重新水化先前持久状态的函数。默认使用storage。
  • setState :将被调用来保持给定状态的函数。默认使用storage。
  • filter :将被调用来过滤将setState最终触发存储的任何突变的函数。默认为() => true

3.获取持久化数据(比如登录页)

login() {
    this.$store.dispatch('loginApi', data).then(res => {
		uni.reLaunch({
			url: '/pages/index/index'
		});
	})
}


4.使用state(比如个人主页):

<template>
	<view>
		<text>{
   
   {id}}</text> 
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	export default {
		data() {
			return {}
		},
		computed: {
			...mapState(["id"),
		},
	}
</script>

二、本地存储实现

代码如下(示例):

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

总结

本文仅仅简单介绍了vuex持久化的使用,插件或者本地缓存两种方式

猜你喜欢

转载自blog.csdn.net/qq_35755436/article/details/129139623