Home > database >  Css switch statement
Css switch statement

Time:10-14

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?

CodePudding user response:

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>

demo 1

Or for improved rendering performance, compute a new item list that includes a class property whose value is the result of getClass():

<template>                                              
  • Related