简体   繁体   中英

How to bind array in DOM using Vue.js

I am working on an application where I bind the list of data into DOM using Vue.js. But it is not working I have used v-for, v-list, and v-repeat but don't get it working. Here is my code both for the template and the script.

 <div class="weather-info" v-if="weather!=undefined">
    <div v-repeat="item in weather">
    
    <div class="location-box">
     <div class="location">{{item.day}}
     </div>
     <!-- <div class="date">{{ todaysDate() }}</div> -->
    </div>

    <div class="weather-box">
     <div class="temp">{{ Math.round(item.temprature) }}°c</div>
     <div class="weather">{{Math.round(item.windSpeed)}}</div>
     <div class="icon">
       <img src="{{iconUrl}}.png"/>
     </div>
    </div>
    </div>
   </div>

Here is the code of the Script

export default {
 data() {
  return {
   url_base: "https://localhost:7197/api/weather/",
   weather: undefined,
  };
 },
 methods :  {

    async fetchWeather(e) {
if (e.key == "Enter") {
let response = await axios.get(`${this.url_base}forecast?city=${this.query}`);
this.setResults(response.data);
}
},
setResults(res) {
 console.log(res)
 if(res.isSuccessful === true){
    this.weather = res.response;
 }else{
 // error message
 }
},
},
};

The JSON i received in res is show below.

在此处输入图像描述

Please try to use v-for instead of v-repeat, you can replace it as follow:

<div v-for="(item, key) in weather" :key="key">
   {{ item }}
   ...
</div>

Your code should work fine, Just wondering from where you are invoking the fetchWeather method. I just created a working demo below. Please have a look and try to find the root cause of the issue.

Just for a demo purpose I am using mock data but you can replace that with an API call.

 new Vue({ el: '#app', data: { weather: undefined }, mounted() { this.weather = [ { day: 'Day 1' }, { day: 'Day 2' }, { day: 'Day 3' }, { day: 'Day 4' } ] } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div class="weather-info" v-if="weather && weather.length"> <div v-for="(item, index) in weather":key="index"> {{ item.day }} </div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM