Search code examples
vue.jsvuejs2v-for

How to bind retrieved data from v-for to data object in Vuejs?


I need to bind data retrieved with v-for (passed via props from parent) to data object. I tried with v-modal but i could not make it work. I am using OpenWeatherApi and I need to store only today's date so I can change it to another format.

So how can i store {{ data.dt }} in "time" in my data object?

<template>
  <div>
      <h2 v-for="(date, index) in filteredList" :key="index" :bind:date="myDate">
          {{date.dt}}
      </h2>
      
  </div>
</template>

<script>
    export default {
        name: 'TodayDate',
        props: [
            "weather"
        ],
        data() {
            return {
                myDate: '',
                time: '',
                today: '',
                isToday: '',
                weekDay: '',
                date: '',
                month: ''
            }
        },
        created() {
            this.getCurrentDate()
        },
        methods: {
            getCurrentDate() {
                this.myDate = new Date(this.time * 1000)
                this.today = new Date(),
                this.isToday = (this.today.toDateString() == this.myDate.toDateString()) ? 'today' : '';
                this.weekDay = this.myDate.toLocaleString('default', { weekday: 'short' })
                this.date = this.myDate.toLocaleString('default', { day: 'numeric' })
                this.month = this.myDate.toLocaleString('default', { month: 'short' })
            }
        },
        computed: {
            filteredList() {
                return this.weather.slice(0, 1);
            },
        }
    }
</script>

Thank you.


Solution

  • Do not assign any property values inside template's v-for loop. Instead create another computed property which will compute the value you need.

    computed: {
      todayDate() {
        if (this.filteredList && this.filteredList.length) {
          return this.fileredList[0].dt
        }
      }
    }
    

    If you need this value to be directly in the component's data object, subsequently create a watcher.

    watch: {
      todayDate(todayDate) {
        this.myDate = todayDate
      }
    }