Vue.js VUEX 属性未定义问题 [英] Vue.js VUEX property undefined issue
问题描述
我遇到了有趣的错误.Chrome 的控制台显示属性 'name' 未定义,但 Vue 工具显示 getter 工作正常.下面的图片...
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...
这是我的 Vue 工具.看看吸气剂.
and here is my Vue tool. Look at the getters.
这里也是我的 store.js 代码
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;
}
}
});
和组件代码
export default {
methods:{
selectCity(){
if(this.city==""){
return this.city="New York"
}
}
},
computed:{
getLocation(){
return this.$store.getters.city;
}
},
}
推荐答案
你的初始状态
state: {
data: "",
location: "New York"
}
将 data
设置为空字符串.这很可能是导致错误的原因
sets data
to an empty string. This is most probably what's producing the error due to
state.data.city.name
其中 city
在 String
上未定义.
where city
is undefined on a String
.
将您的初始状态 data
设置为在异步数据加载之前不会导致错误的内容
Set your initial state data
to something that's not going to cause errors before your async data has loaded
data: {
city: {
name: ''
}
}
<小时>
或者(因为上面的内容似乎扰乱了你的其他逻辑),改变你的 getter 以容忍空数据
getters: {
city (state) {
return state.data.city && state.data.city.name || ''
}
}
这篇关于Vue.js VUEX 属性未定义问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!