Vue.js中如何将v-for遍历获取的数据绑定到data对象?
问题解决方法
首先明确你的核心需求是把OpenWeather返回的时间戳dt赋值给data中的time字段,再做日期格式转换,你原来的代码有两个核心问题:
created生命周期执行时,父组件传入的weatherprops大概率还没有值(接口请求是异步的),此时调用日期转换方法拿到的都是空值- 没有主动把遍历拿到的
date.dt赋值给time字段,自然无法绑定到data中
具体修改方案
你可以直接通过watch监听weather props的变化,拿到值之后直接赋值给time再调用日期转换方法即可,不需要用v-model也不需要在模板里做绑定操作:
1. 脚本部分修改
<script> export default { name: 'TodayDate', props: ["weather"], data() { return { myDate: '', time: '', today: '', isToday: '', weekDay: '', date: '', month: '' } }, watch: { // 监听weather props变化,有值之后再执行逻辑 weather: { immediate: true, // 组件初始化时如果已经有weather值也会触发 handler(newVal) { if (!newVal || !newVal.length) return // 直接取第一个元素的dt赋值给time this.time = newVal[0].dt // 赋值完成后再调用日期转换方法 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也可以删掉 computed: { filteredList() { return this.weather.slice(0, 1); }, } } </script>
2. 模板部分简化
因为你只需要取第一个元素的时间戳,不需要循环遍历,模板可以直接改成:
<template> <div> <!-- 直接取转换后的日期字段渲染即可 --> <h2>{{weekDay}} {{date}} {{month}} {{isToday ? '(今日)' : ''}}</h2> </div> </template>
如果确实需要保留原来的循环逻辑也可以,不需要额外绑定属性,直接渲染对应值就行。
内容的提问来源于stack exchange,提问作者Lakius
相关产品推荐
相关产品推荐

