【发布时间】:2019-02-11 16:48:14
【问题描述】:
我正在尝试使用 Axios 执行 GET 请求,但在控制台中收到以下错误:
TypeError: Cannot set property 'films' of undefined
at eval (SearchBar.vue?e266:26)
搜索栏.vue
<template>
<section>
<input v-model='film' type='text' list='films'>
<datalist id='films'>
<option v-for='film in films' :key='film.episode_id'>{{film}}</option>
</datalist>
</section>
</template>
<script>
import axios from "axios";
export default {
name: "SearchBar",
data() {
return {
film: "",
films: []
};
},
created() {
axios
.get("https://swapi.co/api/films/")
.then(function(response) {
// handle success
//console.log(response);
this.films = response.data.results;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
};
</script>
谁能告诉我为什么会出现错误?注意:我在本地运行它以通过 Vue-Cli 进行即时原型设计
【问题讨论】:
-
错误很清楚,您的
films属性是undefined。尝试添加一些细节,尝试 console.log 你的 axios 响应。我认为response.data.results是undefined然后当你的films在你的循环中使用时,它会失败。 -
看起来我不能在不使用粗箭头的情况下使用“this”?
标签: vuejs2 axios html-datalist