鉴于以下 HTML、CSS 和 Vue 代码片段,我希望能够使用 Vue 2 中的计算属性动态构建一系列 CSS 样式类,并将它们绑定(bind)到已经具有面板类的范围-图标。如 CSS 片段所示,类名应采用 .icon--toolname 的形式,其中工具名是从 JSON 的 toolName 属性中获取的。当我尝试将 for 循环的结果保存到一个变量并返回该变量时,我只得到一个结果,而不是我期望的四个。总体思路是 CSS icon-- 类应该匹配通过 v-for 循环显示的工具名称。
HTML:
<div class="container" id="lab">
<a class="panel-block" v-for="tool in tools">
<span class="panel-icon" :class="style">
<i class="fas fa-book" aria-hidden="true"></i>
</span>
{{ tool.toolName }}
</a>
</div>
CSS:
.icon--bulma {
color: hsl(171, 100%, 41%);
}
.icon--jgthms {
color: hsl(204, 86%, 53%);
}
.icon--marksheet {
color: hsl(48, 100%, 67%);
}
.icon--minireset {
color: hsl(348, 100%, 61%);
}
Vue.js:
new Vue({
el: '#lab',
data: {
tools: [
{
toolName: 'bulma'
},
{
toolName: 'marksheet'
},
{
toolName: 'minireset'
},
{
toolName: 'jgthms'
}
]
},
computed: {
style: function () {
var toolsList = this.tools;
var toolNameStyle = '';
for (var i = 0; i < toolsList.length; i++) {
toolNameStyle = 'icon--' + toolsList[i].toolName;
console.log('toolNameStyle: ' + toolNameStyle);
return toolNameStyle;
}
}
}
})
最佳答案
不需要计算属性,只需做:
<span :class="'panel-icon icon--' + tool.toolName">
关于javascript - Vue.js 中的动态样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50571088/