这个 v-for 指令发生了什么

What happen to this v-for directive

我想做一些像下面这样的对象

所以,一开始我写了下面的代码

<div class="p-2 border-2 border-blue-300 mr-auto rounded-full space-x-1">
    <button class="text-white w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-yellow-400 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-orange-400 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-green-800 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-sky-500 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-red-500 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-purple-600 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-gray-300 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
    <button class="text-black w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"><i class="fa-solid fa-circle"></i></button>
</div>

但是,是的..效率不高。所以,我想我可以使用 v-for 指令来简化这段代码。如下所示。

在模板中

<div class="p-2 border-2 border-blue-300 mr-auto rounded-full space-x-1">
    <button v-for="level in LevelList" :key="level" :class="`text-${level} w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue`"><i class="fa-solid fa-circle"></i></button>
</div>

在脚本中

export default {
    setup() {

        const LevelList = ['white', 'yellow-400', 'orange-400', 'green-800', 'sky-500', 'red-500', 'purple-600', 'gray-300', 'black']

        return {
            LevelList,
        }
    }
}

然而,结果却不同。编写代码后,当我激活 'npm run dev' 结果如下所示。

我错过了什么?

通过分析,这个问题似乎发生在 LevelList 的所有名称中带有短划线的元素。

可能 javascript 将 yellow-400 视为算术表达式 (value of yellow) - 400 而不是简单的字符串

尝试重命名您的 multi-word 元素,看看是否可行!