我有一个Vue对象,其中有一组项作为数据(在我的例子中是FlightPlans)。
到目前为止,该列表已正确呈现。
现在问题来了。我想在使用v-for
对列表中的每个项(flightplan)迭代时应用不同的样式,这取决于当前迭代flightplan memeberfplType
的值。
当前所有列表项(flightplans)都得到类flightplan-list-ifr-dep
。
但我需要类似的东西(伪代码):
<li v-for="flightplan in flightplans"
v-bind:id="flightplan.id"
v-bind:class="{
flightplan-list-ifr-dep: flightplan.fplType === 'departure',
flightplan-list-ifr-arr: flightplan.fplType === 'arrival'
}"
>
因此,每个项都从当前迭代flightplan的fpltype获取其应用的类。
<div id="flightplan-list-area" class="flightplan-list-area-style">
<ul>
<li v-for="flightplan in flightplans"
v-bind:id="flightplan.id"
@click="selected(flightplan, $event)">
<div class="flightplan-list-ifr-dep">
<p class="flightplan-list-ifr-dep-callsign">{{ flightplan.callsign }}</p>
<p class="flightplan-list-ifr-dep-aircraft-type">{{ flightplan.aircraft_type }}</p>
<p class="flightplan-list-ifr-dep-aircraft-wtc">{{ flightplan.aircraft_wtc }}</p>
</div>
</li>
</ul>
</div>
<script lang="javascript">
var vue_FLIGHTPLAN_MODEL = new Vue({
el: "#flightplan-list-area",
data: {
flightplans: [],
selected_flightplan_element: null,
},
});
</script>
最佳答案
您的语法几乎是正确的,但是由于类名包含“-”字符,您只需在v-bind:class
中引用它们:
...
v-bind:class="{
'flightplan-list-ifr-dep': flightplan.fplType === 'departure',
'flightplan-list-ifr-arr': flightplan.fplType === 'arrival'
}"
...
现场演示
var vue_FLIGHTPLAN_MODEL = new Vue({
el: "#flightplan-list-area",
data: {
flightplans: [
{ id: 1, callsign: 'ABC', aircraft_type: 'Boeing 737', aircraft_wtc: 'xyz', fplType: 'departure' },
{ id: 2, callsign: 'DEF', aircraft_type: 'Boeing 737', aircraft_wtc: 'uvw', fplType: 'arrival' },
{ id: 3, callsign: 'HIJ', aircraft_type: 'Boeing 737', aircraft_wtc: 'abc', fplType: 'departure' },
],
selected_flightplan_element: null,
},
methods: {
selected (plan, e) {
this.selected_flightplan_element = plan;
}
},
});
li.flightplan-list-ifr-dep {
color: blue;
}
li.flightplan-list-ifr-arr {
color: green;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="flightplan-list-area" class="flightplan-list-area-style">
<ul>
<li v-for="flightplan in flightplans"
v-bind:id="flightplan.id"
v-bind:class="{
'flightplan-list-ifr-dep': flightplan.fplType === 'departure',
'flightplan-list-ifr-arr': flightplan.fplType === 'arrival'
}"
@click="selected(flightplan, $event)">
<div class="flightplan-list-ifr-dep">
<p class="flightplan-list-ifr-dep-callsign">{{ flightplan.callsign }}</p>
<p class="flightplan-list-ifr-dep-aircraft-type">{{ flightplan.aircraft_type }}</p>
<p class="flightplan-list-ifr-dep-aircraft-wtc">{{ flightplan.aircraft_wtc }}</p>
</div>
</li>
</ul>
</div>