[英]Dynamic Styles in Vue.js
Given the following snippets of HTML, CSS, and Vue code I would like to be able to construct a series of CSS style classes dynamically using a computed property in Vue 2 and bind them to the span that already has a class of panel-icon. 给定以下HTML,CSS和Vue代码片段,我希望能够使用Vue 2中的计算属性动态构造一系列CSS样式类,并将它们绑定到已经具有panel-icon类的范围。 As seen in the CSS snippet, the class name should be in the form of .icon--toolname where toolname is grabbed from the toolName property in the JSON. 从CSS片段中可以看出,类名称应采用.icon--toolname的形式,其中从JSON中的toolName属性获取工具名。 When I try to save the results of the for loop to a variable and return that variable I get only one result, instead of the four that I am expecting. 当我尝试将for循环的结果保存到一个变量并返回该变量时,我只会得到一个结果,而不是我期望的四个结果。 The overall idea is that the CSS icon-- class should match the tool name that is being displayed via the v-for loop. 总体思路是CSS图标类应与通过v-for循环显示的工具名称匹配。
HTML: 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: 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: 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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.