在 Vue.js 中混合动态 class 和数据绑定
Mix Dynamic class with data binders in Vue.js
所以我在 HTML 中有以下 v-for:
<ul v-for="(item, index) in openweathermap.list">
<li>{{item.dt_txt}}</li>
<li>{{item.weather[0].description}}</li>
<li>{{item.weather[0].id}}</li>
<li>{{item.main.temp}}°C</li>
</ul>
我想做的是给这些信息加上一个图标,比如font awesome。
所以我找到了这些:<i class="owf owf-200"></i>
这对我来说正好,但数字必须动态变化。所以数字是 v-for.
中的 {{item.weather[0].id}}
我的问题是这样的;我怎样才能将这两者混合在一起?
我试过这样的东西<i class="owf owf-{{item.weather[0].id}}"></i>
但它显然有错误的语法。
任何帮助将不胜感激!
您可以使用 v-bind:class
- 它允许您附加两个字符串,就像在 Javascript 中一样。所以值应该是 'owf owf-' + item.weather[0].id
.
在代码片段中,我使用虚拟数据和两个不同 类 的颜色更改完成了此操作,但您应该明白了。
var app = new Vue({
el: "#app",
data:{
items: [
{
weather: [{ id: 200 }],
txt: "Some text"
},
{
weather: [{ id: 300 }],
txt: "Some other text"
}
]
}
});
.owf.owf-200 {
color: red;
}
.owf.owf-300 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
<template v-for="item in items">
<span v-bind:class="'owf owf-' + item.weather[0].id">
{{ item.txt }}
</span>
<br />
</template>
</div>
所以我在 HTML 中有以下 v-for:
<ul v-for="(item, index) in openweathermap.list">
<li>{{item.dt_txt}}</li>
<li>{{item.weather[0].description}}</li>
<li>{{item.weather[0].id}}</li>
<li>{{item.main.temp}}°C</li>
</ul>
我想做的是给这些信息加上一个图标,比如font awesome。
所以我找到了这些:<i class="owf owf-200"></i>
这对我来说正好,但数字必须动态变化。所以数字是 v-for.
{{item.weather[0].id}}
我的问题是这样的;我怎样才能将这两者混合在一起?
我试过这样的东西<i class="owf owf-{{item.weather[0].id}}"></i>
但它显然有错误的语法。
任何帮助将不胜感激!
您可以使用 v-bind:class
- 它允许您附加两个字符串,就像在 Javascript 中一样。所以值应该是 'owf owf-' + item.weather[0].id
.
在代码片段中,我使用虚拟数据和两个不同 类 的颜色更改完成了此操作,但您应该明白了。
var app = new Vue({
el: "#app",
data:{
items: [
{
weather: [{ id: 200 }],
txt: "Some text"
},
{
weather: [{ id: 300 }],
txt: "Some other text"
}
]
}
});
.owf.owf-200 {
color: red;
}
.owf.owf-300 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
<template v-for="item in items">
<span v-bind:class="'owf owf-' + item.weather[0].id">
{{ item.txt }}
</span>
<br />
</template>
</div>