【问题标题】:loop with if statement in vuejs在 vuejs 中使用 if 语句循环
【发布时间】:2019-05-06 07:25:35
【问题描述】:

我正在尝试创建一个循环来显示带有 if 语句的按钮和另一个按钮,但主循环一直提供 3 个按钮而不是一个,但是当我删除 else 语句时代码工作正常,那么错过在哪里

<ul class="list-group">
  <li class="list-group-item"
      v-for="orderedLesson in orderedLessonsInSeries"
      :class=" orderedLesson.id == lesson.id ? 'active' : '' ">
    <span class="col-11 text-left">
      <button v-for="userCompletedLesson in userCompletedLessons"
        v-if="userCompletedLesson.id == orderedLesson.id"
        style="text-decoration: none; border: none; background-color: transparent;">
        <i class="fa fa-check-circle fa-lg"></i>
      </button>
      <button v-else style="text-decoration: none; border: none; background-color: transparent;">
        <i class="fa fa-circle-o fa-lg"></i>
      </button>
      <strong>{{ orderedLesson.title }}</strong>
    </span>
  </li>
</ul>

【问题讨论】:

标签: laravel laravel-5 vue.js vuejs2 vue-component


【解决方案1】:

v-if 和 v-for 之间存在混合。如果要检查课程是否完成,可以创建一个单独的方法:

<span class="col-11 text-left">
  <button
    v-if="isCompleted(orderedLesson)"
    style="text-decoration: none; border: none; background-color: transparent;">
    <i class="fa fa-check-circle fa-lg"></i>
  </button>
  <button v-else style="text-decoration: none; border: none; background-color: transparent;">
    <i class="fa fa-circle-o fa-lg"></i>
  </button>
  <strong>{{ orderedLesson.title }}</strong>
</span>

isCompleted方法

methods: {
  isCompleted (lesson) {
    let completedLessonIds = []
    if (this.userCompletedLessons) {
      completedLessonIds = this.userCompletedLessons.map(l => l.id) // you can move it to computed properties
    }
    return completedLessonIds.includes(lesson.id)
  }
}

【讨论】:

    猜你喜欢
    • 2015-07-06
    • 2014-03-13
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2018-11-04
    相关资源
    最近更新 更多