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

时间:2019-06-11 15:07:47

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

我正在使用此Weather API构建天气应用。我试图添加一个<input>字段值,当它更改城市名称时,然后更新其他值预测。

我创建了<input>字段,该字段会更新城市值,并且应该相应地更新天气预报。我知道v-model在工作,但是它不会改变数据结果。仅当我在Vue-instance中对另一个城市进行硬编码时,数据才会更新更改。

<template>
  <div class="home">
    <h1>{{ msg }}</h1>
    <p>A weather app built Vuejs & Open Weather App. Made by Manuel Abascal</p>
    <input type="text" v-model.lazy="currentWeather.name">
    <div class="forecast">
     <div v-if="this.currentWeather">
      <!-- Forecast stat values -->
      <h2>Right now:</h2>
      <div><strong>City:</strong> {{ currentCity }}</div>
      <div><strong>Longitude: </strong> {{ currentWeather.coord.lon }}</div>
      <div><strong>Latitude: </strong> {{ currentWeather.coord.lat }}</div>
      <div><strong>Weather condition </strong> {{ currentWeather.weather[0].description }}</div>
      <div><strong>Temperature Mid: </strong> {{  currentWeather.main.temp }} Farenheit</div>
      <div><strong>Temperature Max: </strong> {{  currentWeather.main.temp_max}} Farenheit</div>
      <div><strong>Temperature Min: </strong> {{  currentWeather.main.temp_min}} Farenheit</div>
      <div><strong>Humidity: </strong> {{  currentWeather.main.humidity }}%</div>
      <div><strong>Wind: </strong> {{  currentWeather.wind.speed }} mph</div>
     </div>
    </div>
  </div>
</template>

<script>
// import Axios
import axios from "axios"

export default {
  name: "Home",
  props: {
    msg: String,
  },
  data(){
    return {
      // current weather
      currentWeather: null,
      // current city
      currentCity: 'Montreal',
      // current country
      currentCountry: 'ca',
      unit: 'imperial'
    }
    this.$set(this.currentCity);
  },
  mounted(){
    // Make axios request to open weather api
    axios.get('https://api.openweathermap.org/data/2.5/weather?q='+this.currentCity+','+this.currentCountry+'&appid=fe435501a7f0d2f2172ccf5f139248f7&units='+this.unit+'')
    .then((response) => {
        // takes response object & stores it in currentWeather
        this.currentWeather = response.data

    })
    .catch(function (error) {
        // handle error
        console.log(error);
    })
  }
};
</script>

<style scoped lang="scss">

</style>

当我更改为蒙特利尔,多伦多,渥太华,艾伯塔省等城市时,我正在尝试。它会相应地更改预测。我需要帮助。

3 个答案:

答案 0 :(得分:1)

您没有currentCity更改的事件处理程序。因此,您的代码将在初始加载时工作(即在mounted上工作,并且更改为currentCity不会更改任何天气数据。

您需要将@change添加到输入中,并在每次更改时获取新的api数据。

下面是示例代码

new Vue({
  el: '#app',
  data() {
    return {
      // current weather
      currentWeather: null,
      // current city
      currentCity: 'Montreal',
      // current country
      currentCountry: 'ca',
      unit: 'imperial'
    }
    this.$set(this.currentCity);
  },
  methods: {
    getWeather() {
      // Make axios request to open weather api
      fetch('https://api.openweathermap.org/data/2.5/weather?q=' + this.currentCity + ',' + this.currentCountry + '&appid=fe435501a7f0d2f2172ccf5f139248f7&units=' + this.unit + '')
        .then(res => res.json()).then(data => {
          // takes response object & stores it in currentWeather
          this.currentWeather = data;

        })
        .catch(function(error) {
          // handle error
          console.log(error);
        })
    }
  },
  mounted() {
    this.getWeather();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div class="home">
    <p>A weather app built Vuejs & Open Weather App. Made by Manuel Abascal</p>
    Search: <input type="text" v-model.lazy="currentCity" @change="getWeather">
    <div class="forecast" v-if="currentWeather && currentWeather.cod == 200">
      <!-- Forecast stat values -->
      <h2>Right now:</h2>
      <div><strong>City:</strong> {{ currentWeather.name }}</div>
      <div><strong>Longitude: </strong> {{ currentWeather.coord.lon }}</div>
      <div><strong>Latitude: </strong> {{ currentWeather.coord.lat }}</div>
      <div><strong>Weather condition </strong> {{ currentWeather.weather[0].description }}</div>
      <div><strong>Temperature Mid: </strong> {{ currentWeather.main.temp }} Farenheit</div>
      <div><strong>Temperature Max: </strong> {{ currentWeather.main.temp_max}} Farenheit</div>
      <div><strong>Temperature Min: </strong> {{ currentWeather.main.temp_min}} Farenheit</div>
      <div><strong>Humidity: </strong> {{ currentWeather.main.humidity }}%</div>
      <div><strong>Wind: </strong> {{ currentWeather.wind.speed }} mph</div>
    </div>
    <div v-else>
      "{{ currentCity }}" is not found
    </div>
  </div>
</div>

答案 1 :(得分:1)

有两个主要问题使您的代码无法按预期工作。

v模型

输入中的v-model应该是currentCity数据值,而不是API响应中的值currentWeather.name

这样,当输入更改时,currentCity将被更新,您可以对它的更改做出反应并请求新数据。

请求数据

mounted钩子中完成对天气的请求仅一次获取数据就很好了,因为在组件使用期内不会再次执行此钩子,因此城市变更将不会发生。什么都不做。

解决方案

我将v-model更改为currentCity,并在currentCity上添加了一个观察者,因此当它发生变化时,它会触发对获取天气的函数的调用,此观察器立即运行,将保证它也可以在组件安装上运行。

我有一个jsfiddle here,其中包含更新的代码。

答案 2 :(得分:1)

您有两个问题:

首先,将输入绑定为currentWeather.name而不是currentCity

第二,在已安装的生命周期中有axios请求。即使currentCity模型发生了变化,您也没有定义什么 当它改变时将会发生。当currentCity更改时,您需要添加一个api调用。

  1. 将输入模型更改为currentCity <input type="text" v-model="currentCity">

  2. 将axios请求移动到自己的方法

    getWeather() {
        const url = 'https://api.openweathermap.org/data/2.5/weather?q=' + this.currentCity + ',' + this.currentCountry + '&appid=fe435501a7f0d2f2172ccf5f139248f7&units=' + this.unit + '';
        axios.get(url)
            .then((response) => {
                this.currentWeather = response.data;
            })
            .catch(function(error) {
                console.log(error);
            })
    }
    
  3. 将输入更改绑定到getWeather方法

您可以将getWeather事件添加到currentCity输入的输入方法中。

<input type="text" v-model="currentCity" @input="getWeather">

或添加当前天气的观察者

watch: {
    currentCity: function(newCity, oldCity) {
        this.getWeather();
    }
}

奖金

每次写下或删除输入字母时,该方法都会触发。添加一个反跳或超时,它将在毫秒后触发。

// import Axios
import axios from "axios"

export default {
    name: "Home",
    props: {
        msg: String,
    },
    data() {
        return {
            currentWeather: null,
            currentCity: 'Montreal',
            currentCountry: 'ca',
            unit: 'imperial'
        };
    },
    watch: {
        currentCity: function(newCity, oldCity) {
            this.debounceGetWeather();
        },
    },
    mounted() {
        this.getWeather();
    },
    methods: {
        debounceGetWeather() {
            setTimeout(() => {
                this.getWeather();
            }, 300);
        },
        getWeather() {
            axios.get('https://api.openweathermap.org/data/2.5/weather?q=' + this.currentCity + ',' + this.currentCountry + '&appid=fe435501a7f0d2f2172ccf5f139248f7&units=' + this.unit + '')
                .then((response) => {
                    this.currentWeather = response.data '
                })
                .catch(function(error) {
                    console.log(error);
                })
        },
    },
};
相关问题