點燈坊

戦わなければ、勝てない

由 Computed 切換 CSS Class

Sam Xiao's Avatar 2023-11-25

實務上 CSS Class 可能會根據 JavaScript 的邏輯而改變,此時可將 CSS Class 綁定到 Computed,並將邏輯寫在 Computed 內。

Version

Vue 2.7

String

<template>
  <div>
    <div :class="titleColor">Hello World</div>
    <button @click="onRed">Red</button>
    <button @click="onBlue">Blue</button>
  </div>
</template>

<script>
let TitleColorEnum = {
  Blue: 0,
  Red: 1,
}

export default {
  data:() => ({
    color: TitleColorEnum.Blue
  }),
  computed: {
    titleColor() {
      switch(this.color) {
        case TitleColorEnum.Blue:
          return { blue: true }
        case TitleColorEnum.Red:
          return { red: true }
      }
    }
  },
  methods:{
    onRed() {
      this.color = TitleColorEnum.Red
    },
    onBlue() {
      this.color = TitleColorEnum.Blue
    }
  }
}
</script>

<style scoped>
.red {
  color: red;
}

.blue {
  color: blue;
}
</style>

Line 2

<div>
  <div :class="titleColor">Hello World</div>
  <button @click="onRed">Red</button>
  <button @click="onBlue">Blue</button>
</div>
  • 將 CSS class 綁定到 titleColor computed
  • 由 button 切換 紅色藍色

Line 10

let TitleColorEnum = {
  Blue: 0,
  Red: 1,
}
  • 定義 TitleColorEnum enum 避免寫死 string

Line 16

data:() => ({
  color: TitleColorEnum.Blue
}),
  • 設定 color data,並由 TitleColorEnum 設定預設值

Line 29

methods:{
  onRed() {
    this.color = TitleColorEnum.Red
  },
  onBlue() {
    this.color = TitleColorEnum.Blue
  }
}
  • 由 button 切換 color data

Line 19

computed: {
  titleColor() {
    switch(this.color) {
      case TitleColorEnum.Blue:
        return 'blue'
      case TitleColorEnum.Red:
        return 'red'
    }
  }
},
  • titleColor computed 可根據 color data 與邏輯決定 CSS class
  • CSS class 可直接以 string 回傳

Object

<template>
  <div>
    <div :class="titleColor">Hello World</div>
    <button @click="onRed">Red</button>
    <button @click="onBlue">Blue</button>
  </div>
</template>

<script>
let TitleColorEnum = {
  Blue: 0,
  Red: 1,
}

export default {
  data:() => ({
    color: TitleColorEnum.Blue
  }),
  computed: {
    titleColor() {
      switch(this.color) {
        case TitleColorEnum.Blue:
          return { blue: true }
        case TitleColorEnum.Red:
          return { red: true }
      }
    }
  },
  methods:{
    onRed() {
      this.color = TitleColorEnum.Red
    },
    onBlue() {
      this.color = TitleColorEnum.Blue
    }
  }
}
</script>

<style scoped>
.red {
  color: red;
}

.blue {
  color: blue;
}
</style>

Line 19

computed: {
  titleColor() {
    switch(this.color) {
      case TitleColorEnum.Blue:
        return { blue: true }
      case TitleColorEnum.Red:
        return { red: true }
    }
  }
},
  • CSS class 亦可以 object 回傳,但須加上 true

Conclusion

  • 如多國語言時,最理想當然一個 CSS class 可以應付所有語言,但若調整真有難度時,亦可為特定語言調整 CSS class,然後根據特定語言動態切換 CSS class