vuex 调试的问题

项目中使用vuex 调试css,刷新页面的时候会vuex里的状态也会刷新,给调试带来很大的麻烦,有什么好的办法吗?

回答:

store.js
想用 sessionstorage cookie 都可以自己设置

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import state from './state'
import {vuexToLocalStorage } from 'tools.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
  //vuex 数据本地localStorage 存储
  plugins: [vuexTolocalStorage]
})

tool.js

export const ls = {
    //本地存数据,days 有效时间(天)
    setItem: function(key, value, days) {
        let Days = Days || 30; //有效时间默认30天
        let exp = new Date();
        let expires = exp.getTime() + Days * 24 * 60 * 60 * 1000;

        localStorage.setItem(key, JSON.stringify({
            value,
            expires
        }));

    },
    getItem: function(key) {
        let o = JSON.parse(localStorage.getItem(key));

        if (!o || o.expires < Date.now()) {
            return null
        } else {
            return o.value
        }
    },
    removeItem: function(key) {
        localStorage.removeItem(key)
    }
}

export const copy = (obj) => {
    let copy = Object.create(Object.getPrototypeOf(obj));
    let propNames = Object.getOwnPropertyNames(obj);
    propNames.forEach(function(name) {
        let desc = Object.getOwnPropertyDescriptor(obj, name);
        Object.defineProperty(copy, name, desc);
    });
    return copy;
}


export const vuexToLocalStorage = store => {
    // 当 store 初始化后调用
    let savedState = ls.getItem('vuex');
    if (savedState) {
        store.replaceState(savedState);
    }
    store.subscribe((mutation, state) => {
        // 每次 mutation 之后调用
        // mutation 的格式为 { type, payload }
        let storeClone = copy(state);
        ls.setItem('vuex', storeClone);
    })
}

export default {
    vuexToLocalStorage,
}

用插件吧

回答:

如过是两个页面传值的话 那刷新就会重置, 你可以吧他放到cookie 或者localStorage里面当页面刷新的时候就不会改变

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注