Vuex getter返回undefined

时间:2018-06-07 00:33:15

标签: javascript vue.js vuex

我有一个使用vex存储网站范围数据的vue应用程序我获取用户信息并将其置于创建生命周期方法之前的状态,如下所示:

const app = new Vue({
    el: '#app',
    store,
    beforeCreate(){
        store.dispatch('currentUser');
    }
});

在我的用户模块中,我有一个获取用户名的getter,如下所示:

const getters = {
    getName(state){
        return state.user.name;
    }
};

在我的组件中,我试图访问getter以显示组件中用户的名称。当我查看Vue Chrome开发工具时,getter不是未定义的,但是当我控制日志时,getter结果就像是未定义的那样。

mounted(){
    console.log(store.getters.getName);
},

在加载状态之前,组件似乎正在加载。我正在使用axios获取用户信息。我真的很困惑如何解决这个问题,因为我无法在我知道的情况下尽快调用该行动来获取用户数据。

如果在我的getter方法中,我会这样做:

state.user

我明白了:

{ "id": 1, "name": "Test" }

但是当我试图获得名字时,我得到了未定义的

这是商店:

import axios from "axios/index";

const state = {
    user: {},
};

const mutations = {
    FETCH_USER(state,user){
        state.user = user;
    },
    UPDATE_AVATAR(state,avatar){
        state.user.avatar = avatar;
    }
};

const getters = {
    getName(state){
      return state.user.name
    },
    avatar(state){
        return state.user.avatar;
    },
    userSocialNetworks(state){
        //return state.user.social_networks
    },
    schoolName(state){
        return state.user.school
    },
    schoolAbout(state){
        return state.user.school.about
    },
    schoolAddress(state){
        return state.user.school.address
    }
};

const actions = {
    currentUser: ({commit}) => {
        axios.get('/api/user').then(response => {
            commit('FETCH_USER', response.data);
        });

    }
}

export default {
    state,
    getters,
    actions,
    mutations

}


 {"user":{"user":{"name":"Test","email":"test@test.edu","avatar":"http://www.gravatar.com/avatar/xxxx=300","city":null,"state":null,"zip":null,"address":null,"lat":null,"long":null,"role":"school","school":{"id":1,"about":null,"header":null,"name":"Test","user_id":1,"created_at":"2018-06-06 19:48:16","updated_at":"2018-06-06 19:48:16"},"following":[],"followers":[],"social_networks":[{"id":4,"user_id":1,"social_network_id":1,"network_url":"test.com/k","created_at":"2018-06-06 23:11:09","updated_at":"2018-06-06 23:15:19"},{"id":5,"user_id":1,"social_network_id":2,"network_url":"test.com/k","created_at":"2018-06-06 23:15:19","updated_at":"2018-06-06 23:15:19"},{"id":6,"user_id":1,"social_network_id":5,"network_url":"test.com/k","created_at":"2018-06-06 23:16:15","updated_at":"2018-06-06 23:16:15"}]}},"socialNetowrks":{"available_networks":[{"id":1,"network_name":"Facebook","created_at":null,"updated_at":null},{"id":2,"network_name":"Instagram","created_at":null,"updated_at":null},{"id":5,"network_name":"Twitter","created_at":null,"updated_at":null}]}}

4 个答案:

答案 0 :(得分:1)

您在这里面临两个大问题:

  1. 您不应直接在vuex存储中更新对象,否则会失去反应性

因此,请确保正确声明所有状态,并分配给对象,而不是覆盖它们

import assignDeep from 'assign-deep'; //Since you have nested structure you will need this

const state = {
    user: {
       name: '',
       school: {
          about: '',
          address: '',
       },
       // Make sure all properties are defined
    },

};

const mutations = {
    FETCH_USER(state,user){
        assignDeep(state.user, user);
    },
    UPDATE_AVATAR(state,avatar){
        state.user.avatar = avatar;
    }
};
  1. 您正在尝试访问在状态上异步定义的属性并同步使用(在存在之前)

首先使用vuex的mapGetters实用程序以方便使用

import { mapGetters } from 'vuex';
//... In component definition
computed: {
  ...mapGetters({name: 'getName'})
}

由于这是一个vue计算属性,因此您的组件在定义时将重新呈现,并且所有内容均应正确显示,您只需要确保在空的情况下处理该情况,并可能一直显示加载屏幕即可,直到

例如

<template>
  <div v-if="!name" class="loading"></div>
  <div v-else>{{name}}</div>
<template>

您还可以等待属性更新

请勿在安装的挂钩中使用它,因为它仍将是其中的默认值

根据您的需要使用watcher or a computed property

watch: {
  name: {
    handler(name, oldName) {
      if (name) {
        //Do something
      }
    },
    immediate: true
  }
}

答案 1 :(得分:0)

首先,方法尚未在beforeCreate钩子中初始化。最简单的方法就是使用created挂钩代替:

const app = new Vue({
    el: '#app',
    store,
    created(){
        store.dispatch('currentUser'); // considering you have properly imported and exported vuex
    }
});

在您的组件中

import {mapGetters} from 'vuex';

export default {
  computed: {
    ...mapGetters(['getName'])
  }
}

答案 2 :(得分:0)

您可以尝试以下方法:

mounted() {
  setTimeout(() => {
    console.log(store.getters.getName);
  }, 400);
},

答案 3 :(得分:0)

尝试在存储中声明特定变量以正确初始化数据:

const state = {
    user: {
        name: '',
        avatar: '',
        school: '',
        ...
    },
};

在执行此操作之前,我遇到了与您描述的问题相同的问题。