【问题标题】:Vue.js dynamic class variable in variableVue.js 变量中的动态类变量
【发布时间】:2023-01-19 03:51:51
【问题描述】:

我想问你,是否可以用这样的动态类来做到这一点。 <div :class="'outofstock.item_' + item.id ? 'bg-green-500' : 'bg-red-500' "> 如果存在解决方案,我无法为此找到正确的语法。谢谢你的回答。

这就是我尝试做的一个例子。我需要 outofstock.item_1、outofstock.item_2 和 outofstock.item_3 在 :claas 中的结果

<template>
<ul>
    <li v-for="item in items">
        <div :class="'outofstock.item_' + item.id ? 'bg-green-500' : 'bg-red-500' ">
            {{ item.name }}
        </div>
    </li>
</ul>
</template>

<script>   
    export default {
        data () {
            return {
                items: [{id: 1, name: 'monitor'}, {id: 2, name: 'printer'},{id: 3, name: 'scanner'],
                outofstock: {item_1: false, item_2: true, item_3: false}
            }
        }
    }
</script>

【问题讨论】:

  • 那么你想要outofstock.item_1还是outofstock.item_1 bg-green-500还是bg-green-500

标签: css vue.js variables


【解决方案1】:

定义一个计算属性,该属性返回一个以项目 ID 作为参数的函数,然后使用字符串模板呈现正确的类:

<template>
<ul>
    <li v-for="item in items">
        <div :class="`${getItemValue(item.id) ? 'bg-green-500' : 'bg-red-500' }`">
            {{ item.name }}
        </div>
    </li>
</ul>
</template>

<script>   
    export default {
        data () {
            return {
                items: [{id: 1, name: 'monitor'}, {id: 2, name: 'printer'},{id: 3, name: 'scanner'],
                outofstock: {item_1: false, item_2: true, item_3: false}
            }
        },
   computed:{
       getItemValue(){
         return (id)=>this.outofstock[`item_${id}`];
       }
     }
    }
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 2018-03-07
    • 1970-01-01
    • 2021-12-29
    • 2015-09-23
    • 2021-02-17
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多