|
| 1 | +<template> |
| 2 | + <view class="nut-collapse"> |
| 3 | + <slot></slot> |
| 4 | + </view> |
| 5 | +</template> |
| 6 | +<script setup lang="ts"> |
| 7 | +import { provide, ref, watch } from 'vue'; |
| 8 | +import { COLLAPSE_KEY, type CollapseValue } from './types'; |
| 9 | +
|
| 10 | +defineOptions({ |
| 11 | + name: 'NutCollapse' |
| 12 | +}); |
| 13 | +
|
| 14 | +export type CollapseProps = Partial<{ |
| 15 | + modelValue: CollapseValue; |
| 16 | + accordion: boolean; |
| 17 | +}>; |
| 18 | +
|
| 19 | +const props = withDefaults(defineProps<CollapseProps>(), { |
| 20 | + modelValue: '', |
| 21 | + accordion: false |
| 22 | +}); |
| 23 | +
|
| 24 | +const emit = defineEmits(['update:modelValue', 'change']); |
| 25 | +
|
| 26 | +const innerValue = ref(props.modelValue || (props.accordion ? '' : [])); |
| 27 | +
|
| 28 | +watch( |
| 29 | + () => props.modelValue, |
| 30 | + (val) => { |
| 31 | + innerValue.value = val; |
| 32 | + } |
| 33 | +); |
| 34 | +
|
| 35 | +const changeVal = (val: string | number | Array<string | number>, name: string | number, status = true) => { |
| 36 | + innerValue.value = val; |
| 37 | + emit('update:modelValue', val); |
| 38 | + emit('change', val, name, status); |
| 39 | +}; |
| 40 | +
|
| 41 | +const updateVal = (name: string | number) => { |
| 42 | + if (props.accordion) { |
| 43 | + if (innerValue.value === name) { |
| 44 | + changeVal('', name, false); |
| 45 | + } else { |
| 46 | + changeVal(name, name, true); |
| 47 | + } |
| 48 | + } else { |
| 49 | + if (Array.isArray(innerValue.value)) { |
| 50 | + if (innerValue.value.includes(name)) { |
| 51 | + const newValue = innerValue.value.filter((v: string | number) => v !== name); |
| 52 | + changeVal(newValue, name, false); |
| 53 | + } else { |
| 54 | + const newValue = innerValue.value.concat([name]); |
| 55 | + changeVal(newValue, name, true); |
| 56 | + } |
| 57 | + } else { |
| 58 | + console.warn('[NutUI] <Collapse> 未开启手风琴模式时 v-model 应为数组'); |
| 59 | + } |
| 60 | + } |
| 61 | +}; |
| 62 | +
|
| 63 | +const isExpanded = (name: string | number) => { |
| 64 | + if (props.accordion) { |
| 65 | + return innerValue.value === name; |
| 66 | + } else if (Array.isArray(innerValue.value)) { |
| 67 | + return innerValue.value.includes(name); |
| 68 | + } |
| 69 | + return false; |
| 70 | +}; |
| 71 | +
|
| 72 | +provide(COLLAPSE_KEY, { |
| 73 | + updateVal, |
| 74 | + isExpanded |
| 75 | +}); |
| 76 | +</script> |
0 commit comments