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

嵌套v-for中的v-if/v-show开发环境正常,生产环境渲染失效求助

嵌套v-for中条件渲染在Vue生产环境失效问题解决思路

将Vue项目部署到虚拟主机后,嵌套v-for里的条件渲染(先后试过v-show、v-if)仅在开发环境正常显示,生产环境完全失效。相关代码如下:

<tr v-for="student in students" v-bind:key="student.id"
    class="bg-white border dark:bg-gray-800 dark:border-gray-700 hover:bg-blue-700 hover:text-white">
    <th scope="row" class="border-blue-700 border pl-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">
        {{ student.first_name }} {{ student.last_name }}
    </th>
    <td v-for="exercise in exercises" v-bind:key="exercise.id" class="border-blue-700 text-center border">
        <div v-for="mark in exercise.marks" v-bind:key="mark.id" class="text-black dark:text-white">
            <span v-show="mark.student_id === student.id">{{ mark.score }}</span>
        </div>
    </td>
</tr>

可能的解决方向

  • 统一数据类型匹配:开发环境可能自动隐式转换不同类型的ID(比如数字和字符串),但生产环境的严格模式下会直接判定不相等。把判断条件改成强制类型转换:

    <span v-show="Number(mark.student_id) === Number(student.id)">{{ mark.score }}</span>
    
  • 提前处理数据,简化模板逻辑:当前三层嵌套循环加条件渲染的写法效率低,还容易在生产编译时出问题。建议在computed里预处理数据:

    computed: {
      studentExerciseScores() {
        return this.students.map(student => {
          // 给每个学生匹配对应作业的分数
          const scores = this.exercises.map(exercise => {
            const matchedMark = exercise.marks.find(mark => mark.student_id === student.id)
            return matchedMark ? matchedMark.score : ''
          })
          return { ...student, scores }
        })
      }
    }
    

    模板简化后:

    <tr v-for="student in studentExerciseScores" :key="student.id"
        class="bg-white border dark:bg-gray-800 dark:border-gray-700 hover:bg-blue-700 hover:text-white">
        <th scope="row" class="border-blue-700 border pl-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">
            {{ student.first_name }} {{ student.last_name }}
        </th>
        <td v-for="score in student.scores" :key="score" class="border-blue-700 text-center border">
            {{ score }}
        </td>
    </tr>
    
  • 检查生产环境缓存:虚拟主机的静态资源可能有缓存,导致旧代码未更新。手动清除主机缓存,或者确认Vue构建时已给资源添加哈希后缀(Vue CLI默认会处理)。

  • 排查构建配置:如果自定义了vue.config.js的压缩规则,检查是否因过度优化导致模板变量被意外混淆,还原默认构建配置试试。

内容的提问来源于stack exchange,提问作者felix shava

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:59:28