| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import { reactive, readonly, ref } from 'vue'
- export interface SelectListOption {
- /** 唯一值,用于回调与选中对比 */
- value: string | number
- /** 展示文案 */
- label: string
- /** 可选 icon */
- icon?: string
- }
- export interface SelectListPopupOptions {
- /** 弹窗标题,可选,例如“Language” */
- title?: string
- /** 需要展示的选项列表 */
- options: SelectListOption[]
- /** 默认选中值 */
- defaultValue?: SelectListOption['value']
- /**
- * 选中回调
- * - 点击某一项后立即触发
- * - 同时会自动关闭弹窗
- */
- onSelect?: (value: SelectListOption['value'], option: SelectListOption) => void
- }
- export interface SelectListPopupState {
- visible: boolean
- title: string
- options: SelectListOption[]
- selectedValue: SelectListOption['value'] | null
- }
- const state = reactive<SelectListPopupState>({
- visible: false,
- title: '',
- options: [],
- selectedValue: null,
- })
- const selectHandler = ref<
- ((value: SelectListOption['value'], option: SelectListOption) => void) | null
- >(null)
- const open = (options: SelectListPopupOptions) => {
- state.title = options.title ?? ''
- state.options = options.options ?? []
- state.selectedValue
- = options.defaultValue ?? (options.options?.[0]?.value ?? null)
- selectHandler.value = options.onSelect ?? null
- state.visible = true
- }
- const close = () => {
- state.visible = false
- }
- const select = (option: SelectListOption) => {
- state.selectedValue = option.value
- const handler = selectHandler.value
- if (handler) {
- handler(option.value, option)
- }
- state.visible = false
- }
- export const useSelectListPopup = () => {
- return {
- state: readonly(state),
- open,
- close,
- select,
- }
- }
|