Невозможно установить свойство после запроса Get - Axios и HTML5 datalist - PullRequest
0 голосов
/ 11 февраля 2019

Я пытаюсь выполнить GET-запрос, используя Axios, но получаю следующую ошибку в консоли:

TypeError: Cannot set property 'films' of undefined
at eval (SearchBar.vue?e266:26)

SearchBar.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>

Anyoneподскажите почему я получаю ошибку?Примечание: я запускаю это локально для мгновенного прототипирования через Vue-Cli

1 Ответ

0 голосов
/ 11 февраля 2019
  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, а затем использовать 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);
    });
  }
...