我有一个有趣的错误。 Chrome的控制台表示未定义属性“名称”,但Vue工具显示吸气剂工作正常。下图...
这也是我的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;
}
}
});
组件的代码
export default {
methods:{
selectCity(){
if(this.city==""){
return this.city="New York"
}
}
},
computed:{
getLocation(){
return this.$store.getters.city;
}
},
}
答案 0 :(得分:1)
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 || ''
}
}