【问题标题】:Accessing the data from localstorage from another route with vuex使用 vuex 从另一条路由访问本地存储中的数据
【发布时间】:2020-10-27 14:04:07
【问题描述】:

我从配置面板路由中获取数据,使用 vuex、storeJS 将其设置为本地存储:

     const state = {
      message: [],
      // console.log(message);
      sec: 0,
      // other state
    };
    const getters = {
      message: (state) => {
        // console.log(this.state.message);
    
        return state.message;
      },
    
      sec: (state) => {
        return state.sec;
      },
      // other getters
    };
    
    const actions = {
      setMessage: ({ commit, state }, inputs) => {
        commit(
          'SET_MESSAGE',
          inputs.map((input) => input.message)
        );
    
        return state.message;
      },

  setSec: ({ commit, state }, newSecVal) => {
    commit('SET_TIMEOUT', newSecVal);
    return state.sec;
  },
  // other actions
};
const mutations = {
  SET_MESSAGE: (state, newValue) => {
    state.message = newValue;
    localStorage.setItem('message', JSON.stringify(newValue));  ----->this
  },
  SET_TIMEOUT: (state, newSecVal) => {
    state.sec = newSecVal;
    localStorage.setItem('sec', JSON.stringify(newSecVal));  --->this
  },
  // other mutations
};

export default {
  state,
  getters,
  actions,
  mutations,
};

现在我有一条回家路线,我想在其中显示这个,我怎样才能访问它?

我正在使用 Mapgetters 获取数据(不是本地存储,而是常规状态数据),并且我正在使用它:

computed: {
   

    ...mapGetters({
      message: "message",
      sec: "sec"
    }),

我怎么能告诉他,如果没有(当页面重新加载时)自动从本地存储中获取数据。 这是我的挂载

mounted() {
    this.$store.dispatch("SET_MESSAGE");
    this.$store.dispatch("SET_SEC");
 
    
  },

【问题讨论】:

  • 在变异中,可以像 state.message || localStorage.getItem('消息')
  • 你的意思是什么?

标签: javascript vue.js local-storage vuex vue-router


【解决方案1】:

我建议你使用这个包来保持你的状态和本地存储同步vuex-persistedstate

或者,您可以像这样设置您的状态。

const state = {
  message: localStorage.getItem('message') || [],
  // console.log(message);
  sec: localStorage.getItem('sec') || '',
  // other state
};

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2020-12-28
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2019-09-22
    • 2020-11-26
    • 1970-01-01
    相关资源
    最近更新 更多