首页 > 解决方案 > v-for 中每个项目的点击指示器

问题描述

我有一个嵌套的 v-for,其中子 v-for 中的每个项目都是可点击的。我正在尝试将任何单击的项目推入一个数组并且它运行良好。但是,如果我没有任何迹象表明这些项目被选中,我认为它有点乏味。

例如。
parent v-for工作日(周一至周日)组成,而child v-for由时间(上午 8 点、上午 9 点等...)

所以我像这样渲染它。

HTML

<div v-for"(day,d) in week_days">
    <p>{{day}}</p>
    <hr>
    <small>List of times</small>
    <p v-for="(time,t) in time_list"
        :class={'activeItem ': moment(day).format('MMMM DD YYYY')+' '+time == activeItem}
        @click="selectTime(<time and date object here>)"> {{time}} 
    </p>
</div>

JS

selectTime(obj) {
    this.activeItem = obj.date+' '+obj.time; //2020-10-22 9:30PM
    this.selected_time.push(obj); //not related to the main problem
}

CSS

.active {
    color: red;
}

到目前为止,这个有效,但仅适用于单个项目,而不适用于所有选定项目。

问题是:

  1. 我如何做到这一点,以便所有选定的项目都将被指示/标记为已单击。
  2. 至于指示器/标记,不是将文本着色为红色,而是可以将任何项目替换{{time}}Marked.

标签: javascripthtmlcssvue.js

解决方案


为什么没有一个包含所有已选择项目的计算属性?就像是:

computed: {
  selectedItems() {
    return this.selected_item.map(item => item.format('LLL'))
  }
}

然后在您的模板上,您可以检查是否在 v-for 循环中选择了该项目:

<div v-for"(day,d) in week_days">
    <p>{{day}}</p>
    <hr>
    <small>List of times</small>
    <p v-for="(time,t) in time_list"
        :class={'activeItem ': selectedItems.includes(moment(day).format('LLL'))}
        @click="selectTime(<time and date object here>)"> {{time}} 
    </p>
</div>

推荐阅读