在uniApp中使用vuex && vuex实现数据持久化 您所在的位置:网站首页 vuex本地存储持久化 在uniApp中使用vuex && vuex实现数据持久化

在uniApp中使用vuex && vuex实现数据持久化

2024-07-13 07:23| 来源: 网络整理| 查看: 265

vuex的6大属性有哪些?

注:vuex 中的 namespaces 是什么?它的主要作用是什么?

在Vuex 模块中开启 namespaced 以后,确定该模块为带命名空间的模块。当模块被注册后,它的所有state、getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

Vuex 模块的安装以及配置

1. 执行安装命令

yarn add vuex -S

2. 创建目录

        1)在应用中创建一个目录 store

        2)在此目录中还需要再创建一个目录 modules

        3)在目录 modules 中创建一个文件 index.js

        4)在此文件中写上我们的六大属性,由于需要模块开发,所以需要结构暴露

// 设置状态 const state = { initData: '初始Vuex数据' } // 获取内容 const getters = {} // 修改数据 const mutations = {} // 异步操作 const actions = { async getTodos({commit}){ // this 一定不是VueComponent,而是store实例 // 这就意味着无法使用 this.$u.api const result = await this.vm.$u.api.getTodos() } } export default { namespaced: true, state, getters, mutations, actions }

        5)在store的根目录下再创建一个index.js文件

import Vue from 'vue' import Vuex from 'vuex' import indexModule from './modules/index' Vue.use(Vuex); // 结构暴露 export default new Vuex.Store({ modules:{ indexModule } })

        6) store需要与vue进行关联,在入口文件 main.js 中需要引入仓库内容

import store from './store' const app = new Vue({ ...App, store })

        7)在组件内应用,获取store状态方式

mounted()( // 第一种获取state的方式,直接利用store进行获取 console.log(this.$store.state.indexModule.initData) } import {mapState} from 'vuex' computed:{ // 第二种获取state的方式,利用对象进行函数化返回操作 ...mapState({ initData:state=> state.indexModule.initData }) // 第三种获取state的方式,利用命名空间与状态数组进行映射 ...mapState('indexModule',['initData']) }

        8) 在组件内应用,action的调用方式

// 第一种action的调用方式,直接利用store进行dispatch分发处理 mounted()( this.$store.dispatch('indexModule/getTodos') }, // 第二种action的调用方式,利用命名空间与动作名称的数组 import { mapState ,mapActions } from 'vuex' methods:{ ...mapActions(['indexModule/getTodos']) }, mounted() { this['indexModule/getTodos'](); } // 第三种action的调用方式,利用命名空间与动作数组进行映射 import { mapState ,mapActions } from 'vuex' methods:{ ...mapActions('indexModule',['getTodos']) }, mounted() { this.getTodos(); } // 第四种action的调用方式,利用命名空间与对象进行映射 import { mapState ,mapActions } from 'vuex' methods:{ ...mapActions('indexModule',{ getIndexTodos:'getTodos' }) }, mounted() { this.getIndexTodos(); } vuex的持久化处理

1. 下载插件

yarn add wuex-persistedstate -S

2. 在 store 目录中的 index.js 进行引入,进行插件辅助

import Vue from 'vue' import Vuex from 'vuex' import indexModule from './modules/index' import createPersistedState from "vuex-persistedstate"; Vue.use(Vuex); // 结构暴露 export default new Vuex.Store({ modules:{ indexModule }, plugins: [createPersistedState({ storage: { getItem: (key) => uni.getStorageSync(key), setItem: (key, value) => uni.setStorageSync(key,value), removeItem: key => uni.removeStorageSync(key) })] })


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有