Issue
So, I currently have something like this in vue:
<div class="item" :class="{ priority: item.priority }">
What I want to do is to be able to change my border-color based on the item's priority, so if there's something like a switch statement in CSS that can enable me to achieve this?
Solution
There's no switch statement in CSS, but you could do this in JavaScript, and use a class binding to apply it to the div
.
For instance, use a getClass()
method based on priority:
<template>
<div class="item-list" v-for="item in items">
<div class="item" :class="getClass(item.priority)">...</div>
</div>
</template>
<script>
export default {
⋮
methods: {
getClass(priority) {
switch (priority) {
case 1: return 'high-priority'
case 2: return 'medium-priority'
default: return 'low-priority'
}
}
},
}
</script>
<style scoped>
.high-priority {
border-color: red;
}
.medium-priority {
border-color: orange;
}
.low-priority {
border-color: gray;
}
</style>
Or for improved rendering performance, compute a new item list that includes a class
property whose value is the result of getClass()
:
<template> 👇
<div class="item-list" v-for="item in computedItems">
<div class="item" :class="item.class">...</div>
</div> 👆
</template>
<script>
export default {
⋮
computed: { 👇
computedItems() {
return this.items.map(item => ({
...item,
class: this.getClass(item.priority),
})) 👆
}
}
}
</script>
Answered By - tony19
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.