You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js数组绑定DOM失效求助:使用v-for等指令仍无法渲染

问题排查与解决

核心问题分析

  1. 指令版本不兼容:v-repeat是Vue 1.x的旧指令,Vue 2及以上版本统一使用v-for,你提到尝试过v-for但未生效,核心原因是数据结构匹配错误。
  2. 数据结构不匹配:接口返回的res.response是包含forecast数组的对象,而非直接的数组。你将this.weather赋值为res.response,但模板里直接循环weather(对象),自然无法渲染列表。
  3. 属性插值错误:<img src="{{iconUrl}}.png"/>这种写法在Vue中不生效,属性绑定需用v-bind:src(或简写:src)。
  4. 未定义query变量:fetchWeather中使用了this.query,但data里未声明该变量,会导致请求参数缺失,接口可能返回异常。

修正后的代码

模板部分

<div class="weather-info" v-if="weather && weather.forecast">
  <!-- 循环forecast数组,绑定唯一key -->
  <div v-for="(item, index) in weather.forecast" :key="index">
    <div class="location-box">
      <div class="location">{{ item.day }}</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">
        <!-- 正确绑定图片src -->
        <img :src="`${item.iconUrl}.png`" />
      </div>
    </div>
  </div>
</div>

脚本部分

export default {
  data() {
    return {
      url_base: "https://localhost:7197/api/weather/",
      weather: undefined,
      query: "" // 新增缺失的query变量
    };
  },
  methods : {
    async fetchWeather(e) {
      if (e.key === "Enter" && this.query.trim()) { // 增加空值判断,避免无效请求
        try {
          let response = await axios.get(`${this.url_base}forecast?city=${this.query}`);
          this.setResults(response.data);
        } catch (err) {
          console.error("请求天气数据失败:", err);
        }
      }
    },
    setResults(res) {
      console.log(res);
      if(res.isSuccessful === true){
        this.weather = res.response;
      } else {
        // 可添加错误提示逻辑
        alert("获取天气数据失败,请稍后重试");
      }
    },
  },
};

额外注意事项

  • v-for的key建议使用数组中唯一标识(如接口返回的item.id),用index仅为临时方案,避免列表更新时出现渲染异常。
  • 确保项目已正确引入axios,否则会出现axios is not defined错误。
  • 可优化v-if判断为weather?.forecast?.length,避免空数组时渲染无内容的结构。

内容的提问来源于stack exchange,提问作者Kamran Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:00:58