點燈坊

失くすものさえない今が強くなるチャンスよ

實作簡易 Toggle

Sam Xiao's Avatar 2021-04-10

簡易 Toggle 可設定 truefalse,但必須搭配 JavaScript 維護 State 並動態改變 Utility。

Version

Vue 3.0.5
Tailwind CSS 2.1.1

Simple Toggle

simple000

可簡單 toggle,但必須自行使用 JavaScript 維護 state。

<template>
  <button @click="onClick" type="button" :class="isOn ? 'bg-indigo-600' : 'bg-gray-200'" class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" aria-pressed="false">
    <span class="sr-only">Use setting</span>
    <span aria-hidden="true" :class="isOn ? 'translate-x-5' : 'translate-x-0'" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200"></span>
  </button>
</template>

<script setup>
ref: isOn = true

let onClick = () => isOn = !isOn
</script>

第 2 行

<span @click="onClick" :class="isOn ? 'bg-indigo-600' : 'bg-gray-200'">
</span>
  • 外層 <span> 需攔截 click event 維護 state
  • isOntrue 時使用 bg-indigo-600,否則使用 bg-gray-200,可直接在 :class 內使用 ?: operator

第 4 行

<span :class="isOn ? 'translate-x-5' : 'translate-x-0'"></span>

isOntrue 時使用 translate-x-5,否則使用 translate-x-0,可直接在 :class 內使用 ?: operator

第 9 行

ref: isOn = true

定義 isOn state 初始值為 true

11 行

let onClick = () => isOn = !isOn

onClick() 會對 isOn state 做 toggle。

Function Pipeline

<template>
  <button @click="onClick" type="button" :class="isOn ? 'bg-indigo-600' : 'bg-gray-200'" class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" aria-pressed="false">
    <span class="sr-only">Use setting</span>
    <span aria-hidden="true" :class="isOn ? 'translate-x-5' : 'translate-x-0'" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200"></span>
  </button>
</template>

<script setup>
import { ref } from 'vue'
import { pipe, not } from 'ramda'
import { read, write } from 'vue3-fp'

let isOn = ref(true)

let onClick = pipe(
  read(isOn),
  not,
  write(isOn)
)
</script>

15 行

let onClick = pipe(
  read(isOn),
  not,
  write(isOn)
)
  • read(isOn):讀取 isOn state
  • not():對 isOn state 做 toggle
  • write(isOn):寫入 isOn state

Conclusion

  • Simple Toggle 必須自行攔截 click event 並對 isOn state 做 toggle
  • Tailwind UI 常有兩個 utility 根據 state 改變而切換 utility,可簡單在 :class 內使用 ?: operator