【Vue笔记】 对象数据动态绑定类名 :class

140 阅读1分钟

动态绑定类名 :class 与对象类型数据结合时一个有趣的现象:

<div class="test" :class="{ show: true }">
  测试元素1
</div>
<div class="test" :class="{ show: false }">
  测试元素2
</div>

... 

<style>
  .test {
    display: none;
  }
  .show {
    display: block;
  }
</style>

上述例子运行的结果是:

  • 测试元素1 带有 show 类名,因此显示;
  • 测试元素2 不带有 show 类名,不显示。

得出一个结论:对象类型中值为 true 的键值 key 会被添加到动态类名中。

更直接点,如果这么写:<div :class="{ 123:true, 456:true, 789:false }"></div>,那这个 div 就会有 123 456 这两个类名,不会有789

因此,可以通过控制这个 Boolean 类型的值来巧妙的控制类名:

<div class="test" :class="{ show: innerBoolean }">
  测试元素1
</div>
<button @click="innerBoolean = !innerBoolean">显隐</button>

... 

<script>
  ...
  const innerBoolean = ref(true);

  ...
</script>

...

<style>
  .test {
    display: none;
  }
  .show {
    display: block;
  }
</style>

一旦点击 buttoninnerBoolean 就会“翻转”,这样就能够控制 div 的显示和隐藏。

控制单个 DOM 的类名或者显隐的方法有很多,但这个有趣的用法还可以用在一组元素的 focus / active 上:

<div class="test" 
     v-for="(item, index) in 10"
     :key="index"
     :class="{ focus: index === current }" 
     @click="focusHandle(index)">
  测试元素 {{ index }}
</div>

... 

<script>
  ...
  const current = ref(0) // 默认 focus 0 号

  focusHandle(index) {
    current.value = index
  }

  ...
</script>

...

<style>
  div {
    color: #000;
  }
  .focus {
    color: green;
  }
</style>

这个例子的运行结果:

  • 10 个测试元素;
  • 默认 0 号 测试元素有 focus 类名,是绿色的,其他都是黑色;
  • 点击任意元素都会导致被点击的变绿,剩余其他都是黑色。

这样就实现了控制一组元素的 focus / active 功能。

其他能够实现的功能欢迎在评论区赐教!

笔记主要为自用,欢迎友好交流!