【问题标题】:Cannot access state by getters vuex vuejs无法通过getter vuex vuejs访问状态
【发布时间】:2021-03-28 01:40:49
【问题描述】:

我是 vuex 的新手,我想通过 getter getUser() 方法访问处于状态中的用户对象,我试图调用它 console.log(this.$store.getters.getUser); 在挂载方法中但没有结果。 我试图在突变中控制日志并返回用户对象。 我还关注了文档并搜索了解决方案,但没有任何反应

我还缺少什么?

store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
state: {
    user: {},
},
getters: {
    getUser: state => {
       return state.user
     }
    
},
mutations: {
    auth_user(state,data) {
        state.user = data
    }
 },
actions: {
    fetchAuthUser(context){
        axios.get('/user-data').then(response => {
            context.commit("auth_user",response.data)
        }).catch({});
    }
}, 

 })


 export default store

索引.js

  mounted(){
  // this.auth_user;
   this.getCategories();
   this.$store.dispatch('fetchAuthUser', this.auth_user);
    console.log(this.$store.getters.getUser);
},

【问题讨论】:

  • 试试console.log(this.$store.state.state.user)

标签: laravel vue.js vuex


【解决方案1】:

您的操作是异步的,应该返回一个承诺。

fetchAuthUser(context){
    return axios.get('/user-data').then(response => {
        context.commit("auth_user",response.data)
    }).catch({});
}

在你的mounted中你可以使用then来处理数据。

mounted(){
   // this.auth_user;
   this.getCategories();
   this.$store.dispatch('fetchAuthUser', this.auth_user).then(() => {
      console.log(this.$store.getters.getUser);
   });
}

【讨论】:

  • 那么请考虑接受答案。
猜你喜欢
  • 2021-11-11
  • 2019-11-17
  • 2021-04-14
  • 2018-04-14
  • 2021-06-01
  • 2017-10-01
  • 2021-06-17
  • 1970-01-01
  • 2021-07-17
相关资源
最近更新 更多