【问题标题】:Cannot set property after Get reques - Axios and HTML5 datalist获取请求后无法设置属性 - Axios 和 HTML5 数据列表
【发布时间】: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.resultsundefined 然后当你的 films 在你的循环中使用时,它会失败。
  • 看起来我不能在不使用粗箭头的情况下使用“this”?

标签: vuejs2 axios html-datalist


【解决方案1】:
  1. 一种方法是使用箭头函数:

created() {
  axios
    .get("https://swapi.co/api/films/")
    .then((response) => {
      // handle success
      //console.log(response);
      this.films = response.data.results;
    })
    .catch(function(error) {
      // handle error
      console.log(error);
    });
}
2.另一种方式that = this & 然后在promise回调中使用that

created() {
  const that = this; // <-- assign this in that

  axios
    .get("https://swapi.co/api/films/")
    .then(function (response) {
      // handle success
      //console.log(response);
      that.films = response.data.results;
    })
    .catch(function(error) {
      // handle error
      console.log(error);
    });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2013-08-15
    相关资源
    最近更新 更多