Vue: 使用Vuex 保存 Javascript对象、数组

Vue: vuex保存Javascript对象、数组

在网上找了一大圈,基本就没有专门的一篇博客讲解 Vuex 如何保存
vuex 保存 Javascript对象、数组大致分为以下几个步骤:

  1. 封装 Storage 对象
  2. Vuexstoregettersmutations 中编写保存方法
  3. 利用 JSON.stringify() 方法封装 Javascript 对象、数组为JSON类型
  4. 利用 Vuexgetters 方法获取 Vuex 中保存的值,通过 JSON.prase() 解析封装的JSON值,从而访问 Vuex 保存的对象。

1. 封装 Storage 对象

由于 页面刷新 可能会造成 Vuex 中保存的变量、对象数组 丢失,故将 Vuex 中的存储的状态变量,保存到浏览器缓存 —— sessionStorage 中;并在Vuex的 getters 中获取 sessionStorage 中保存的值,防止页面刷新数据丢失。

storage.js :

const storage = {

    set(key, value) {
        window.sessionStorage.setItem(key, value)
    },
    
    get(key) {
        return window.sessionStorage.getItem(key)
    },

    remove(key) {
        window.sessionStorage.removeItem(key)
    }
    
}

export default storage

2. 在 Vuexstoregettersmutations 中编写保存方法

Vuex.js:

import Vue from 'vue'
import Vuex from 'vuex'
import storage from '../utils/storage'

Vue.use(Vuex)

export default new Vuex.Store({

    state: { // 数据保存在state内,在任何组件内通过this.$store.state.XX来读取
    	// Vuex保存对象
        user: {
            userAccount: null,
            password: null,
        },
        // Vuex保存数组
		demoList: []
    },

    // 用来直接修改state内的数据;在组件内,通过this.$store.commit(方法名)来执行mutations
    // mutations: 本质上是一个对象
    // mutations中主要是改变state初始值的方法, 用法: 通过传入state或额外参数
    // 利用vue的双向驱动进行state中值的修改;
    mutations: {
        createUser(state, user) {
            state.user = user;
        },
		
		setDemoList(state, demoList) {
			state.demoList = demoList
		}
    },

    // 提交的是mutation, 并且可以异步操作
    // 异步触发mutations中的方法
    // action中的自定义函数: 一个context(上下文)以及要变化的 “形参”
    // context与store实例具有相同的方法和属性, 故context.commit('')有效!
    // 作用:存在业务逻辑
    // action在组件内通过this.$store.dipatch(方法名)来触发
    actions: {
        // this.$store.dispatch('createUser');
        commitToken(context) {
            context.commit('createUser');
        },
    },

    // 将各个组件中的computed中的方法提取出来
    // 实时监测state中变量值的变化
    // 可以通过this.$store.state.xxx获取变量值, 但getters更专业(类似于Bean的getter方法)
    getters: {

        // 方法名随意
        // _this.$store.getters.getUser
        getUser(state) {
            state.user = storage.get('user');
            return state.user;
        },
		
		getDemoList(state) {
            state.demoList = storage.get("demoList");
            return state.demoList;
		}

    },

    modules: { // 用来将store分割到不同模块

    }

})

3. 利用 JSON.stringify() 方法封装 Javascript 对象、数组为JSON类型

4. 利用 Vuexgetters 方法获取 Vuex 中保存的值,通过 JSON.prase() 解析封装的JSON值,从而访问 Vuex 保存的对象。

<template>
    <div class="container">
        用户名: <input type="text" v-model="userAccount" placeholder="请输入用户名...">
        密码: <input type="password" v-model="password"  placeholder="请输入密码..">
        <h3>show User:</h3>
        <p>{{showAccount}}</p>
        <p>{{showPassword}}</p>

        <h3>show demoList:</h3>
        <p>{{showList[0].id}}</p>
        <p>{{showList[0].name}}</p>
        <p>{{showList[0].content}}</p>
    </div>
</template>

<script>
import storage from '@/utils/storage';

export default {

    name: "Login",

    components: {
    },

    created() {
        
        var user = new Object();
        user.userAccount = this.userAccount;
        user.password = this.password;

        storage.set('user', JSON.stringify(user));
        this.$store.commit('createUser', storage.get('user'));

        this.showAccount = JSON.parse(this.$store.getters.getUser).userAccount;
        this.showPassword = JSON.parse(this.$store.getters.getUser).password;

        storage.set('demoList', JSON.stringify(this.demooList));
        this.$store.commit('setDemoList', storage.get('demoList'));
        
        this.showList = JSON.parse(this.$store.getters.getDemoList);
        
    },

    data() {

        return {

            userAccount: null,
            password: null,
            showAccount: null,
            showPassword: null,
            demoList: [
                {
                id: 1,
                name: "China",
                content: "hello China!",
                },
                {
                id: 2,
                name: "world",
                content: "hello world!",
                },
            ],

            showList: []

        
        }

    },

    
};
</script>

<style scoped>
</style>

解决数据刷新丢失问题:

将 Javascript 对象封装成 JSON :

封装成JSON:

storage.set('user', JSON.stringify(user));

解析JSON:

var user = JSON.parse(storage.get('user'));

输出观察:

 console.log("----(((-------");
 // console.log(user.userAccount);
 console.log(_this.$store.getters.getUser.userAccount);
 console.log("----)))-------");
 console.log(JSON.parse(_this.$store.getters.getUser).userAccount);
 console.log("----)))-------");

在这里插入图片描述
不使用 JSON.prase() 解析,则无法有效访问 Vuex 中保存的对象、数组。

ps:

最后需要说明的是,Vuex 是一个提升 变量作用范围 的工具,Vuex将 state 当做 全局变量 存储。F5刷新页面之后自然随着页面的刷新重新初始化 state;故刷新后,Vuex中的数据全部丢失!

References

  1. 解决vuex存储复杂参数(如对象数组等)刷新数据丢失问题
  • 8
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值