uniapp vue2 vuex 持久化

1.vuex的使用

一、uniapp中有自带vuex插件,直接引用即可

二、在项目中新建文件夹store,在main.js中导入

在根目录下新建文件夹store,在此目录下新建index.js文件

index.js

javascript 复制代码
import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
		//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
	},
    mutations: {
		//相当于同步的操作
	},
    actions: {
		//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
	}
})
export default store

在main.js中导入挂载vuex

javascript 复制代码
import Vue from 'vue'
import App from './App'
import store from './pages/store/index.js'
Vue.prototype.$store = store


Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
	store,
    ...App
})
app.$mount()

2.使用

第一种方式:this. s t o r e 直接操作例如当取值:直接在页面中使用 t h i s . store直接操作 例如当取值:直接在页面中使用this. store直接操作例如当取值:直接在页面中使用this.store.state.变量名

第二种方法:mapState, mapGetters, mapActions, mapMutations

javascript 复制代码
<template>
    <view class="content">
    
    </view>
</template>

<script>
    import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
    //导入
    export default {
        data() {
            return {
            }
        },
        computed: { //computed中注册
            ...mapGetters(['text1']),
            ...mapState([
                'text1'
            ])
        }
        methods: {
            ...mapMutations([]),
            ...mapActions([])
        }
    }
</script>

<style>
</style>

3.vuex持久化

问题:

H5应用中存在Vuex中的数据在刷新页面后丢失了。

原因:

Vuex的 store 中的数据是保存在运行内存中的,当页面刷新时,页面会重新加载 Vue 实例,Vuex数据会重新初始化,导致页面刷新Vuex中的数据丢失的问题。

解决:

使用 vuex-persistedstate 插件

1、在项目目录下执行:npm install --save vuex-persistedstate;

2、修改store/index.js

javascript 复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from "vuex-persistedstate"

Vue.use(Vuex)

const store = new Vuex.Store({
	plugins: [
		persistedState({
			storage: {
				getItem: key => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: key => uni.removeStorageSync(key)
			}
		})
	],
	state:{//存放状态
        "username":'',
        "userid":''
    },
	mutations:{
		//...
	},
	actions:{
		//...
	},
	//...
})

export default store

使用后浏览器打开用控制台调试可看数据存放在 window.localStorage.vuex

这里其实就和调用uniapp提供的数据缓存API存放的数据位置一样了,官方文档链接:https://uniapp.dcloud.io/api/storage/storage.html

注意:在APP-PLUS环境下,这个数据在应用退出时默认不会被清空(或者说初始化)。

原文链接:https://blog.csdn.net/Mr_Bobcp/article/details/125876232

相关推荐
张元清11 小时前
useEffect 之外:专门处理异步、深比较和 SSR 的 Effect Hook
前端·javascript·面试
XinZong11 小时前
OpenClaw 中最经典的 6 款skill,真正能进工作流的 skills
javascript·后端
XinZong12 小时前
2026 AI社交深度评测:InStreet 与 ClawReach 核心差异解析
javascript
Bug-制造者12 小时前
【Vue3 实战】全局错误处理体系搭建:实现业务与错误彻底解耦
前端·javascript·vue.js
竹林81813 小时前
从ethers.js迁移到Viem:我在DeFi Dashboard项目中踩过的坑与最终方案
javascript
zithern_juejin13 小时前
ES6——Promise
javascript
桜吹雪13 小时前
所有智能体架构(1):反思 (Reflection)
javascript·人工智能
前端那点事14 小时前
Vue3+TS 封装高复用 ECharts 通用组件,自适应+防抖+主题切换,开箱即用
前端·vue.js
前端那点事14 小时前
Vue3+TS动态路由终极方案|后端权限、刷新不丢、按钮权限、解决所有404BUG
前端·vue.js