首页 > 解决方案 > 如何将检索到的数据从 v-for 绑定到 Vuejs 中的数据对象?

问题描述

我需要将使用 v-for 检索到的数据(通过来自父级的道具传递)绑定到数据对象。我尝试使用 v-modal,但无法使其正常工作。我正在使用 OpenWeatherApi,我只需要存储今天的日期,以便将其更改为另一种格式。

那么我怎样才能将 {{ data.dt }} 存储在我的数据对象中的“时间”中?

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

谢谢你。

标签: vue.jsvuejs2v-for

解决方案


不要在模板的v-for循环内分配任何属性值。而是创建另一个计算属性,它将计算您需要的值。

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

如果您需要此值直接位于组件的data对象中,请随后创建一个watcher

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

推荐阅读