Switch组件

介绍

用来打开或关闭选项。

安装

  1. import { createApp } from 'vue';
  2. import { Switch } from '@nutui/nutui';
  3. const app = createApp();
  4. app.use(Switch);

代码演示

基础用法

  1. <nut-switch v-model="checked" />
  1. import { ref } from 'vue';
  2. export default {
  3. setup() {
  4. const checked = ref(true);
  5. return { checked };
  6. },
  7. };

禁用状态

  1. <nut-switch v-model="checked" disable />

change事件

  1. <nut-switch v-model="checked" @change="change" />
  1. import { ref, getCurrentInstance } from 'vue';
  2. export default {
  3. setup() {
  4. let { proxy } = getCurrentInstance() as any;
  5. const checked = ref(true);
  6. const change = (value: boolean, event: Event) => {
  7. proxy.$toast.text(`触发了change事件,开关状态:${value}`);
  8. };
  9. return {
  10. checked,
  11. change
  12. };
  13. }
  14. };

异步控制

  1. <nut-switch :model-value="checkedAsync" @change="changeAsync" />
  1. import { ref, getCurrentInstance } from 'vue';
  2. export default {
  3. setup() {
  4. let { proxy } = getCurrentInstance() as any;
  5. const checkedAsync = ref(true);
  6. const changeAsync = (value: boolean, event: Event) => {
  7. proxy.$toast.text(`2秒后异步触发 ${value}`);
  8. setTimeout(() => {
  9. checkedAsync.value = value;
  10. }, 2000);
  11. };
  12. return {
  13. checkedAsync,
  14. changeAsync
  15. };
  16. }
  17. };

自定义颜色

  1. <nut-switch v-model="checked" @change="switchChange" active-color="blue" />

支持文字

  1. <nut-switch v-model="checked" @change="switchChange" active-text="开" inactive-text="关" />

API

Props

参数说明类型默认值
v-model开关状态Booleanfalse
disable禁用状态Booleanfalse
active-color打开时的背景颜色String#fa2c19
inactive-color关闭时的背景颜色String#ebebeb
active-text打开时文字描述String-
inactive-text关闭时文字描述String-

Events

事件名说明回调参数
change切换开关时触发(value: boolean,event: Event)

Switch  开关组件 - 图1