Back to Vant

Checkbox

packages/vant/src/checkbox/README.md

4.10.010.6 KB
Original Source

Checkbox

Intro

A group of options for multiple choices.

Install

Register component globally via app.use, refer to Component Registration for more registration ways.

js
import { createApp } from 'vue';
import { Checkbox, CheckboxGroup } from 'vant';

const app = createApp();
app.use(Checkbox);
app.use(CheckboxGroup);

Usage

Basic Usage

html
<van-checkbox v-model="checked">Checkbox</van-checkbox>
js
import { ref } from 'vue';

export default {
  setup() {
    const checked = ref(true);
    return {
      checked,
    };
  },
};

Disabled

html
<van-checkbox v-model="checked" disabled>Checkbox</van-checkbox>

Custom Shape

html
<van-checkbox-group v-model="checked" shape="square">
  <van-checkbox name="a">复选框 a</van-checkbox>
  <van-checkbox name="b">复选框 b</van-checkbox>
</van-checkbox-group>
js
import { ref } from 'vue';

export default {
  setup() {
    const checked = ref(['a', 'b']);
    return { checked };
  },
};

Custom Color

html
<van-checkbox v-model="checked" checked-color="#ee0a24">Checkbox</van-checkbox>

Custom Icon Size

html
<van-checkbox v-model="checked" icon-size="24px">Checkbox</van-checkbox>

Custom Icon

Use icon slot to custom icon.

html
<van-checkbox v-model="checked">
  customize icon
  <template #icon="props">
    
  </template>
</van-checkbox>

<style>
  .img-icon {
    height: 20px;
  }
</style>
js
import { ref } from 'vue';

export default {
  setup() {
    const checked = ref(true);
    return {
      checked,
      activeIcon:
        'https://fastly.jsdelivr.net/npm/@vant/assets/user-active.png',
      inactiveIcon:
        'https://fastly.jsdelivr.net/npm/@vant/assets/user-inactive.png',
    };
  },
};

Left Label

Set label-position prop to 'left' to adjust the label position to the left of the Checkbox.

html
<van-checkbox v-model="checked" label-position="left">Checkbox</van-checkbox>

Disable Label Click

html
<van-checkbox v-model="checked" label-disabled>Checkbox</van-checkbox>

Checkbox Group

When Checkboxes are inside a CheckboxGroup, the checked checkboxes's name is an array and bound with CheckboxGroup by v-model.

html
<van-checkbox-group v-model="checked">
  <van-checkbox name="a">Checkbox a</van-checkbox>
  <van-checkbox name="b">Checkbox b</van-checkbox>
</van-checkbox-group>
js
import { ref } from 'vue';

export default {
  setup() {
    const checked = ref(['a', 'b']);
    return { checked };
  },
};

Horizontal

html
<van-checkbox-group v-model="checked" direction="horizontal">
  <van-checkbox name="a">Checkbox a</van-checkbox>
  <van-checkbox name="b">Checkbox b</van-checkbox>
</van-checkbox-group>
js
import { ref } from 'vue';

export default {
  setup() {
    const checked = ref([]);
    return { checked };
  },
};

Maximum amount of checked options

html
<van-checkbox-group v-model="checked" :max="2">
  <van-checkbox name="a">Checkbox a</van-checkbox>
  <van-checkbox name="b">Checkbox b</van-checkbox>
  <van-checkbox name="c">Checkbox c</van-checkbox>
</van-checkbox-group>

Toggle All

html
<van-checkbox-group v-model="checked" ref="checkboxGroup">
  <van-checkbox name="a">Checkbox a</van-checkbox>
  <van-checkbox name="b">Checkbox b</van-checkbox>
  <van-checkbox name="c">Checkbox c</van-checkbox>
</van-checkbox-group>

<van-button type="primary" @click="checkAll">Check All</van-button>
<van-button type="primary" @click="toggleAll">Toggle All</van-button>
js
import { ref } from 'vue';

export default {
  setup() {
    const checked = ref([]);
    const checkboxGroup = ref(null);

    const checkAll = () => {
      checkboxGroup.value.toggleAll(true);
    }
    const toggleAll = () => {
      checkboxGroup.value.toggleAll();
    },

    return {
      checked,
      checkAll,
      toggleAll,
      checkboxGroup,
    };
  },
};

Inside a Cell

html
<van-checkbox-group v-model="checked">
  <van-cell-group inset>
    <van-cell
      v-for="(item, index) in list"
      clickable
      :key="item"
      :title="`Checkbox ${item}`"
      @click="toggle(index)"
    >
      <template #right-icon>
        <van-checkbox
          :name="item"
          :ref="el => checkboxRefs[index] = el"
          @click.stop
        />
      </template>
    </van-cell>
  </van-cell-group>
</van-checkbox-group>
js
import { ref, onBeforeUpdate } from 'vue';

export default {
  setup() {
    const checked = ref([]);
    const checkboxRefs = ref([]);
    const toggle = (index) => {
      checkboxRefs.value[index].toggle();
    };

    onBeforeUpdate(() => {
      checkboxRefs.value = [];
    });

    return {
      list: ['a', 'b'],
      toggle,
      checked,
      checkboxRefs,
    };
  },
};

indeterminate

html
<van-checkbox
  v-model="isCheckAll"
  :indeterminate="isIndeterminate"
  @change="checkAllChange"
>
  Check All
</van-checkbox>

<van-checkbox-group v-model="checkedResult" @change="checkedResultChange">
  <van-checkbox v-for="item in list" :key="item" :name="item">
    Checkbox {{ item }}
  </van-checkbox>
</van-checkbox-group>
js
import { ref } from 'vue';

export default {
  setup() {
    const list = ['a', 'b', 'c', 'd']

    const isCheckAll = ref(false);
    const checkedResult = ref(['a', 'b', 'd']);
    const isIndeterminate = ref(true);

    const checkAllChange = (val: boolean) => {
      checkedResult.value = val ? list : []
      isIndeterminate.value = false
    }

    const checkedResultChange = (value: string[]) => {
      const checkedCount = value.length
      isCheckAll.value = checkedCount === list.length
      isIndeterminate.value = checkedCount > 0 && checkedCount < list.length
    }

    return {
      list,
      isCheckAll,
      checkedResult,
      checkAllChange,
      isIndeterminate,
      checkedResultChange
    };
  },
};

API

Checkbox Props

AttributeDescriptionTypeDefault
v-modelCheck statusbooleanfalse
nameCheckbox name, usually a unique string or numberany-
shapeCan be set to squarestringround
disabledDisable checkboxbooleanfalse
label-disabledWhether to disable label clickbooleanfalse
label-positionCan be set to leftstringright
icon-sizeIcon sizenumber | string20px
checked-colorChecked colorstring#1989fa
bind-groupWhether to bind with CheckboxGroupbooleantrue
indeterminateWhether indeterminate statusbooleanfalse

CheckboxGroup Props

AttributeDescriptionTypeDefault
v-modelNames of all checked checkboxesany[]-
disabledWhether to disable all checkboxesbooleanfalse
maxMaximum amount of checked optionsnumber | string0(Unlimited)
directionDirection, can be set to horizontalstringvertical
icon-sizeIcon size of all checkboxesnumber | string20px
checked-colorChecked color of all checkboxesstring#1989fa
shape v4.6.3Can be set to squarestringround

Checkbox Events

EventDescriptionParameters
changeEmitted when value changedchecked: boolean
clickEmitted when the checkbox is clickedevent: MouseEvent

CheckboxGroup Events

EventDescriptionParameters
changeEmitted when value changednames: any[]

Checkbox Slots

NameDescriptionSlotProps
defaultCustom label{ checked: boolean, disabled: boolean }
iconCustom icon{ checked: boolean, disabled: boolean }

CheckboxGroup Methods

Use ref to get CheckboxGroup instance and call instance methods.

NameDescriptionAttributeReturn value
toggleAllToggle check status of all checkboxesoptions?: boolean | object-

toggleAll Usage

js
import { ref } from 'vue';
import type { CheckboxGroupInstance } from 'vant';

const checkboxGroupRef = ref<CheckboxGroupInstance>();

// Toggle all
checkboxGroup.value?.toggleAll();
// Select all
checkboxGroup.value?.toggleAll(true);
// Unselect all
checkboxGroup.value?.toggleAll(false);

// Toggle all, skip disabled
checkboxGroup.value?.toggleAll({
  skipDisabled: true,
});
// Select all, skip disabled
checkboxGroup.value?.toggleAll({
  checked: true,
  skipDisabled: true,
});

Checkbox Methods

Use ref to get Checkbox instance and call instance methods.

NameDescriptionAttributeReturn value
toggleToggle check statuschecked?: boolean-

Types

The component exports the following type definitions:

ts
import type {
  CheckboxProps,
  CheckboxShape,
  CheckboxInstance,
  CheckboxLabelPosition,
  CheckboxGroupProps,
  CheckboxGroupInstance,
  CheckboxGroupDirection,
  CheckboxGroupToggleAllOptions,
} from 'vant';

CheckboxInstance and CheckboxGroupInstance is the type of component instance:

ts
import { ref } from 'vue';
import type { CheckboxInstance, CheckboxGroupInstance } from 'vant';

const checkboxRef = ref<CheckboxInstance>();
const checkboxGroupRef = ref<CheckboxGroupInstance>();

checkboxRef.value?.toggle();
checkboxGroupRef.value?.toggleAll();

Theming

CSS Variables

The component provides the following CSS variables, which can be used to customize styles. Please refer to ConfigProvider component.

NameDefault ValueDescription
--van-checkbox-size20px-
--van-checkbox-border-colorvar(--van-gray-5)-
--van-checkbox-durationvar(--van-duration-fast)-
--van-checkbox-label-marginvar(--van-padding-xs)-
--van-checkbox-label-colorvar(--van-text-color)-
--van-checkbox-checked-icon-colorvar(--van-primary-color)-
--van-checkbox-disabled-icon-colorvar(--van-gray-5)-
--van-checkbox-disabled-label-colorvar(--van-text-color-3)-
--van-checkbox-disabled-backgroundvar(--van-border-color)-