【问题标题】:Adding class to element in v-for loop在 v-for 循环中向元素添加类
【发布时间】:2022-07-29 01:01:56
【问题描述】:

我有一个 v-for 循环,我想通过添加一个类来创建 background: red;。但是当我单击我的操作按钮时,它会为所有索引着色。 我的 目标 是如果我在单击优先级按钮时有 3 个元素,然后将该行(索引)背景设为红色。我的意思是列表元素使背景变成红色/黄色/绿色。

<div v-for="(item, index) in todos" :key="item.id">
    <div :class="{'bg-red-500': isRed, 'bg-yellow-500': isYellow, 'bg-green-500': isGreen}" class="rounded transition ease-in-out delay-200 duraiton-200 flex align-middle justify-between">

        <div id="checklist" @click="addCompleted(index)" class="w-1/2 break-all text-white transition duration-200 ease-out text-1xl text-left my-5 transition ease-in-out delay-150   duration-200 cursor-pointer flex justify-start align-center">
            <input v-bind:id="item.id" type="checkbox" name="checkbox" class="outline-0 offset-0 ring-0 border-0 focus:outline-0 focus:ring-0 focus:offset-0 focus:border-0 focus:ring-offset-0" />
            <label v-bind:for="item.id">{{ item.text }}</label>
        </div>

        <div class="priority flex items-center justify-between text-white">
            <div @click="priortiy_red(index)" class="red rounded-full bg-red-500 p-2 "></div>
            <div @click="priortiy_yellow(index)" class="yellow rounded-full bg-yellow-500 p-2 mx-2"></div>
            <div @click="priortiy_green(index)" class="green rounded-full bg-green-500 p-2 "></div>
        </div>

        <span class="X-icon  items-center justify-end inline-flex cursor-pointer" @click="removeTodo(index)">
            <svg class="fill-current text-red-500" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                <path d="M0 0h24v24H0z" fill="none" />
            </svg>
        </span>
    </div>
</div>

我现在尝试什么我尝试普通的 vuejs 的类绑定属性。但正如我所说,它为所有部门着色。

Github 回购链接:https://keremunce.github.io/Vue-ToDo/

【问题讨论】:

    标签: vue.js vuejs2 vue-component vuex


    【解决方案1】:

    一个简单的解决方案是为每个待办事项对象添加一个color 属性。

    然后用item.color === 'red'等申请课程。

    ... 'bg-red-500': item.color === 'red', 'bg-yellow-500': item.color === 'yellow', 'bg-green-500': item.color === ''green ...
    

    并应用颜色:

    ...
    @click="item.color = 'red'"
    // etc
    ...
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2021-01-18
      • 2021-12-03
      • 1970-01-01
      • 2016-08-25
      • 2019-12-31
      相关资源
      最近更新 更多