在Vuejs中更改v模型输入值时,动态数据不会更新

时间:2020-05-06 16:12:33

标签: api vue.js data-binding vuejs2 v-model

我正在尝试将参数“ pokemonName”添加到使用axios提取的api url中。我的目标是显示用户在输入文本字段中输入的每个新神奇宝贝的JSON数据。

这是我的HTML:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Pokemon Search</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="style.css">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>

  <div id="app" class="container">

    <div>{{ results }}</div><br />

    Search: <input type="text" v-model.lazy="pokemonName" @change="getPokemon">
  </div>



  <script src="script.js"></script>
</body>

</html>

这是我的js:

new Vue({
  el: '#app',
  data() {
    return {
      results: [],
      pokemonName: ""
    }
    this.$set(this.pokemonName)
  },
  methods: {
    getPokemon() {
      // await axios
      fetch('https://pokeapi.co/api/v2/pokemon/' + this.pokemonName)
        //.then(response => (this.results = response.data));
        .then(response => response.json()).then(data => {
          this.pokemonName = data;
        })
        .catch(function(error) {
          console.log(ERROR);
        })
    }
  },
  mounted: function mounted() {
    this.getPokemon()
  }
});

1 个答案:

答案 0 :(得分:0)

您的代码正常工作。键入数字以查看名称。您需要设置结果。

new Vue({
  el: '#app',
  data() {
    return {
      results: [],
      pokemonName: ""
    }
    this.$set(this.pokemonName)
  },
  methods: {
    getPokemon() {
      // await axios
      fetch('https://pokeapi.co/api/v2/pokemon/' + this.pokemonName)
        //.then(response => (this.results = response.data));
        .then(response => response.json()).then(data => {
          this.results = data.name;
        })
        .catch(function(error) {
          console.log(ERROR);
        })
    }
  },
  mounted: function mounted() {
    this.getPokemon()
  }
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Pokemon Search</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="style.css">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>

  <div id="app" class="container">

    <div>{{ results }}</div><br /> Search: <input type="text" v-model.lazy="pokemonName" @change="getPokemon">
  </div>

</body>

</html>

相关问题