<div v-for="(item, index) in $store.state.category" :key="index"> <div class="bg">{{ item.category | showFirst }}</div> <div class="name">{{ item.category }}</div> </div>,对class=‘“bg”添加背景颜色。
时间: 2023-12-16 16:06:38 浏览: 111
要为`class="bg"`的元素添加背景颜色,你可以使用内联样式绑定的方式来实现。以下是一个示例:
```html
<template>
<div>
<div v-for="(item, index) in $store.state.category" :key="index">
<div class="bg" :style="{ backgroundColor: item.backgroundColor }">
{{ item.category | showFirst }}
</div>
<div class="name">{{ item.category }}</div>
</div>
</div>
</template>
<script>
export default {
computed: {
$store() {
return this.$store;
}
},
filters: {
showFirst: function(value) {
return value.charAt(0);
}
},
mounted() {
this.$store.state.category.forEach((item) => {
item.backgroundColor = getRandomColor();
});
}
};
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
```
在上面的示例中,我们使用`v-for`指令遍历`$store.state.category`数组,并为每个循环项`item`添加了一个`backgroundColor`属性。在`mounted`钩子函数中,我们为每个循环项设置了随机的背景颜色。
然后,我们使用`:style`指令将`backgroundColor`属性与`item.backgroundColor`关联起来,从而为`class="bg"`的元素添加背景颜色。
请注意,上述示例中的`getRandomColor`函数用于生成随机的背景颜色。你可以根据需要自定义生成颜色的逻辑。
最后,我们还添加了一个名为`showFirst`的过滤器,用于仅显示每个类别的第一个字符。你可以根据需要自定义过滤器的逻辑。
阅读全文
相关推荐

















