【问题标题】:Commit objects to state in vuex将对象提交到 vuex 中的状态
【发布时间】:2018-03-27 23:03:36
【问题描述】:

我正在尝试通过 $store.commit('fetchFunction', response.data) 从 axios 响应中获取对象。我需要 computed 在 App.vue (根组件)中将数组“全局”存储在 SPA (vue-router)中。 这就是我得到的。

auth.js

axios.get('/api/to/userController/id')
    .then(response => {

    //this is a nice json
    console.log(response.data.data);
    app.$store.commit('userProfile', response.data.data)
    })
    .catch(error => {

    console.log(error);
    });

store.js

state: {
    userProfile: {}
},
mutations: {
    userProfile (state, payload) {
        state.userProfile = payload;
    }
},
getters: {
    userProfile: state => {

    //this is [__ob__: Observer] lenght: 0
    console.log(state.userProfile)}
    return state.userProfile;
}

App.vue

created() {

    //this is filled with the observer from store.js - Until reload page!
    //after reload page - it is null!
    console.log();
},
computed: {

    userProfile() {
        return this.$store.getters.UserProfile;
    }
}

我的实际问题是,如果我更改路由或重新加载页面,该对象将成为观察者,store 不会存储它。 我以前有几乎相同的功能,只是使用true 和false(我用JWT Token 处理身份验证的状态),它就像一个魅力。 我的问题是以一种很好的方式传递对象。

【问题讨论】:

  • 使用会话存储
  • 不错的解决方案!这是我喜欢的一种方式,而且效果很好!谢谢

标签: javascript ecmascript-6 vue.js axios vuex


【解决方案1】:

使用SessionStorage 通过路由更改来跟踪更改。

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2020-05-30
    • 2019-08-17
    • 2020-09-10
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多