sard-uniapp
Version:
sard-uniapp 是一套基于 Uniapp + Vue3 框架开发的兼容多端的 UI 组件库
62 lines (61 loc) • 1.8 kB
JavaScript
import { provide, ref, toRef, toValue } from 'vue';
import { selectContextSymbol, } from './common';
export function useSelect(props) {
const innerValue = ref(props.multiple ? [] : undefined);
const selectItems = ref([]);
const register = (selectItem) => {
if (!selectItems.value.includes(selectItem)) {
selectItems.value.push(selectItem);
}
};
const unregister = (selectItem) => {
const index = selectItems.value.indexOf(selectItem);
if (index !== -1) {
selectItems.value.splice(index, 1);
}
};
const getEnabledValue = () => {
return selectItems.value
.filter((item) => !toValue(item.disabled))
.map((item) => item.value());
};
let onToggle;
let onSelect;
const toggle = (value) => {
let nextValue;
if (props.multiple) {
nextValue = innerValue.value.includes(value)
? innerValue.value.filter((val) => val !== value)
: innerValue.value.concat(value);
}
else {
if (value === innerValue.value) {
onSelect?.(value);
return;
}
nextValue = value;
}
onToggle?.(nextValue);
onSelect?.(value);
};
const setToggle = (toggle) => {
onToggle = toggle;
};
const setSelect = (select) => {
onSelect = select;
};
const context = {
innerValue,
toggle,
multiple: toRef(() => props.multiple),
multipleLimit: toRef(() => props.multipleLimit),
register,
unregister,
getEnabledValue,
selectItems,
setToggle,
setSelect,
};
provide(selectContextSymbol, context);
return context;
}