Skip to content

Switch 开关

表示两种相互对立的状态间的切换,多用于触发「开/关」。

基础用法

绑定 v-model 到一个 Boolean 类型的变量。 可以使用 --cb-switch-on-color 属性与 --cb-switch-off-color 属性来设置开关的背景色。

<script setup>
import { ref } from 'vue'
import { CbSwitch as Switch } from '@ptpchips/carbon-ui'
const test = ref(true)
</script>
<template>
  <Switch v-model="test" @click="test = !test" />
</template>

禁用状态

设置 disabled 属性,接受一个 boolean,设置true即可禁用。

正常:

禁用:
<script setup>
import { ref } from 'vue'
import { CbSwitch as Switch } from '@ptpchips/carbon-ui'
const test = ref(false)
const test2 = ref(false)
</script>
<template>
  <div class="switch-box">正常:<Switch v-model="test" /> <br /></div>
  <div class="switch-box">禁用:<Switch v-model="test2" disabled /></div>
</template>

<style scoped>
.switch-box {
  display: flex;
  align-items: center;
}
</style>

不同尺寸和颜色

设置 size 属性,接受large / small,呈现不同的尺寸。

设置 active-colorinactive-color 属性,接受 string 类型的值,设置开关的背景色。

<script setup>
import { ref } from 'vue'
import { CbSwitch as Switch } from '@ptpchips/carbon-ui'
const test = ref(false)
</script>
<template>
  <div class="switch-size-container">
    <Switch v-model="test" size="large" active-color="#41B883" inactive-color="lightblue" />
    <Switch v-model="test" active-color="gold" />
    <Switch v-model="test" size="small" active-color="yellowgreen" inactive-color="#888888" />
  </div>
</template>
<style scoped>
.switch-size-container {
  display: flex;
  align-items: center;
  .cb-switch {
    margin-right: 10px;
  }
}
</style>

支持自定义 value 类型

你可以设置 active-valueinactive-value 属性, 它们接受 boolean | string | number 类型的值。

model-value: right

<script setup>
import { ref } from 'vue'
import { CbSwitch as Switch } from '@ptpchips/carbon-ui'
const test = ref('right')
</script>
<template>
  <Switch v-model="test" activeValue="right" inactiveValue="wrong" />
  <h4>model-value: {{ test }}</h4>
</template>

文字描述

使用 active-text 属性与 inactive-text 属性来设置开关的文字描述。

OFF
<script setup>
import { ref } from 'vue'
import { CbSwitch as Switch } from '@ptpchips/carbon-ui'
const test = ref(false)
</script>
<template>
  <Switch v-model="test" activeText="ON" inactiveText="OFF" style="width: 50px" />
</template>