Implementing Vue.js to bind arrays in the DOM

I have been working on a new project where I am trying to bind a list of data into the DOM using Vue.js. Unfortunately, despite my attempts with v-for, v-list, and v-repeat, I can't seem to get it to work properly. Below you can see both the template code and the script code that I am using.

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

Below is the script code:

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 shown below.

https://i.sstatic.net/RE53I.png

Answer №1

Your code seems to be functioning correctly, I'm just curious where you are calling the fetchWeather method from. To help you troubleshoot, I've created a demo below for reference.

For demonstration purposes, I am using mock data in this example, but you can easily replace it 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>

Answer №2

It's recommended to utilize v-for instead of v-repeat in your code. You can achieve this by updating it as shown below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to dynamically override inline styles?

My HTML code is as follows: <div title="remove css"style="position:relative;">Remove my style</div> After the page loads, I need to completely remove the position style attribute. Due to limitations, I cannot override the CSS. Is there a way ...

JavaScript is having trouble with the custom attribute (data-) in HTML and it is not functioning

I created a select bar with multiple options to help me sort items, and I also wanted to add a feature where clicking the option again switches between ascending and descending order. Here is the HTML code snippet: <select name="theme" id="sortSelec ...

In Google Apps Script, JavaScript is used to identify each character in an array as true by implementing the method ".hasOwnProperty(i)"

Behold the following array: {"C8_235550": {"listing":"aut,C8_235550_220144650654"}, "C8_231252": {"listing":"aut,C8_231252_220144650654"}} This data was retrieved via a GET request from a Firebase database using Google Apps Script. var optList ...

Tips for preventing users from entering special characters into input fields

How can I prevent users from entering the # character into an HTML input field? I attempted to use the pattern attribute, but it does not seem to be effective. I included this pattern in my input element: pattern="[^-#]+" I expected that this would disa ...

Ways to continuously monitor an array until specific criteria are fulfilled

My goal is to search for a specific item in an array called idarray and loop through it until I find a value that is not equal to -1. Once I find that value, I want to use the index to retrieve the corresponding value from another array called array. To a ...

Is there another way to implement this method without having to convert snapshotChanges() into a promise?

When trying to retrieve cartIdFire, it is returning as undefined since the snapshot method is returning an observable. Is there a way to get cartIdFire without converting the snapshot method into a promise? Any workaround for this situation? private asyn ...

Guide to adding personalized SVG symbols to Vuetify 3

Looking to import custom SVG icons in Vuetify 3 and Nuxt 3? In Vuetify 2, we could import SVG icons directly like this import customIcon from './myIcon.vue' Vue.use(Vuetify) export default new Vuetify({ icons: { iconfont: 'mdi', ...

How to play two audio files at the same time on iOS Safari

I encountered a unique challenge in Javascript when attempting to play two audio files simultaneously on iOS Safari. One file is the voice script, while the other serves as background sound playing on loop. The code snippet I utilized for this task is as f ...

Is it possible to have a complex V-If statement within a computed property?

Struggling to manage a complex v-if statement within the template as it's becoming overwhelming. After moving the statement into a computed property, an error occurs during evaluation. Any suggestions? <div v-for="offer in offers" class="grid-4 ...

Exploring JSON data with JQuery: A comprehensive guide to looping through with each

I am currently facing an issue with looping through cached JSON data obtained from an Ajax call. Specifically, I keep receiving the error message 'Cannot read property 'title' of undefined'. Can someone provide assistance? $.each(cach ...

The deferredZoneUpdate method in Tapestry's JavaScript, within the zoneManager's callback function

I have integrated a fullcalendar in my Tapestry 5.4 web page. Whenever I create a new Event or click on an existing event, it triggers the fullcalendar's method (select or eventClick). These methods then call a Tapestry JS method (zoneManager.deferre ...

Sending Functions as Props in React Using Typescript from a Parent Component to a Child Component

Trying to pass props from Parent to Child using TypeScript-React but getting an error: "Type 'void' is not assignable to type 'Function'." Parent import React from "react"; import Navbar from "./navbar"; import Main from "./main"; f ...

Updating to a newer version of jQuery causes issues with pop-out submenus

Looking for a way to create a menu with pop-out submenus? Here's an example using jQuery: <script type="text/javascript"> $(document).ready(function() { var hoverAttributes = { speed: 10, delay: 1 ...

triggering the bootstrap datetimepicker's onChange event when selecting start and end dates

In my project, I have implemented a bootstrap datetimepicker for selecting start and end dates, along with switch buttons to quickly set dates for today, last week, and all time. Here is how it looks: https://i.sstatic.net/nE39s.png For the datetimepicke ...

I am encountering an unspecified variable error in Ionic and I cannot determine the cause

I'm attempting to perform encryption and decryption of a basic text in Ionic. Below is the code snippet I am using: encryptedData : any; encryptData(data){ this.aes .encrypt(this.secureKey, this.secureIV, data) .then(res => { ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

After the checkbox is clicked, I must send a boolean value to the function through the input flag in AngularJS

<input class="bx--toggle" id="toggle-view" type="checkbox" ng-model="vm.monthView" ng-change="vm.getRelevantData()" ng-attr-data-modal-target="{{vm.alertForSaveAll ? '#add-save-all-alert-modal': 'undefined'}}"> Within this p ...

Is it possible to set a maximum distance for Three.js FogExp2?

Can I set a maximum distance for the application of FogExp2, which takes in color and density parameters? I'm facing an issue where the color of the Sun (drawn using THREE.SphereGeometry) is being overridden by the fog color. Is there a way to preven ...

Is the statement true in JavaScript if either true or true or false?

I have implemented this code snippet to prevent my page from being iframed: window.onload = function(){ try { if (window.parent && window.parent.location.hostname !== "app.herokuapp.com"){ throw new Error(); } catch (e){ //do something ...

How to Retrieve Results Using Async in Node.js Module?

I am currently developing an internal NPM module for my company to enable applications to communicate with a hardware device using an existing library. The challenge I am facing is implementing a method that must execute asynchronously. This function shoul ...