在vuejs中使用if语句循环

时间:2018-12-04 19:35:24

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

我正在尝试创建一个循环,以显示带有if语句的按钮和else时的另一个按钮,但是主循环一直提供3个按钮而不是一个按钮,但是当我删除else语句时,代码可以正常工作,所以miss在哪里< / p>

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

1 个答案:

答案 0 :(得分:0)

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