DEV Community

Cover image for Vue | v-bind:class&style 不同的表示法
周柏諭 BO-YU CHOU
周柏諭 BO-YU CHOU

Posted on

1 1

Vue | v-bind:class&style 不同的表示法

1. 物件的表示 Object Syntax

<div v-bind:class="{a: isA, b: isB}"></div>
Enter fullscreen mode Exit fullscreen mode
data: {
  isA: true,
  isB: false
}
Enter fullscreen mode Exit fullscreen mode

這裡對 a 和 b 這兩個名稱的class,分別指定 isA 和 isB 的 Vue屬性名稱,改變這兩個屬性的value(bool),即可以控制這個div標籤套用哪個class樣式,輕鬆實現toggle class。

2. 陣列的表示 Array Syntax

<div v-bind:class="[activeClass, errorClass]"></div>
Enter fullscreen mode Exit fullscreen mode
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}
Enter fullscreen mode Exit fullscreen mode

如果想實現toggle class

<div v-bind:class="[isA ? activeClass : '', errorClass]"></div>
Enter fullscreen mode Exit fullscreen mode

又或者結合物件

<div v-bind:class="[{ activeClass: isA }, errorClass]"></div>
Enter fullscreen mode Exit fullscreen mode

https://vuejs.org/v2/guide/class-and-style.html

Top comments (1)

Collapse
 
kissu profile image
Konstantin BIFERT

Another way of writing things could also be: :class="{ isA && a, isB && b}", keeps the things in the same directory so it's quite handy!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay