Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I got interesting bug. Chrome's console says that property 'name' is undefined but Vue tool is showing that getters are working properly. Images below...enter image description here

and here is my Vue tool. Look at the getters. enter image description here

also here is my code for store.js

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import { api } from "./api_key";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
  data: "",
  location: "New York"
},
mutations: {
  GET_DATA(state, data) {
    state.data = data;
  }
},
actions: {
  getData({ commit, state }) {
    console.log(api);
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/forecast/daily?q=${
          state.location
         }&appid=${api}&units=metric&cnt=5`
      )
      .then(response => {
        if (response.data) {
          commit("GET_DATA", response.data);
        }
      })
      .catch(function(error) {
        console.log(error);
      });
  }
},
getters: {
  city(state) {
    return state.data.city.name;
  }
}
});

and code of the component

export default {
    methods:{
        selectCity(){
            if(this.city==""){
                return this.city="New York"
            }
        }
    },
    computed:{
        getLocation(){
            return this.$store.getters.city;
        }
    },
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your initial state

state: {
  data: "",
  location: "New York"
}

sets data to an empty string. This is most probably what's producing the error due to

state.data.city.name

where city is undefined on a String.

Set your initial state data to something that's not going to cause errors before your async data has loaded

data: {
  city: {
    name: ''
  }
}

Alternatively (and because the above appears to mess up your other logic), change your getter to be forgiving of empty data

getters: {
  city (state) {
    return state.data.city && state.data.city.name || ''
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...