﻿# nf-lazy-select {#lazy-select}

Adds asynchronous pagination, search, value echo, request aliases, cross-page selection caching, deferred initialization, loading and error events to nf-virtual-select.

## Examples {#examples}

### Pagination, virtual scrolling and multiple selection {#example-1}

### Pagination, virtual scrolling and multiple selection
```vue
<template>
  <NfConfigProvider theme="chalk" locale="en-US">
<div>
    <!-- request 👈 定制分页请求方法，要求返回promise<{records: any[], total:number}>,入参({[pageNoAlias]: number，[pageSizeAlias]: number，[keywordAlias]: string}) -->
    <!-- pageSize 👈 定制每次分页请求数量 -->
    <!-- virtual-list 👈 默认不开启虚拟滚动，设置true开启 -->
    <!-- keeps 👈 默认30，定制虚拟滚动最多真实渲染的下拉项数量 -->
    <!-- key-value 👈 list每个数据项渲染对应的label和value对应的prop，类型[string, string],默认值['label', 'value'] -->
    <!-- data-key 👈 虚拟滚动要求在list每个数据项有一个唯一值，该属性用以指定数据项唯一值对应的prop，类型string -->

    <div class="select-demo">
  <div class="select-demo-result"><pre>{{ test }}</pre></div>
  <div class="select-demo-controls">
<NfLazySelect
        v-model="test"

        :request="testPage"
        :page-size='10'
        keyword-alias="keyword"
        page-no-alias="pageNo"
        page-size-alias="pageSize"

        loading-desc='Loading...'
        no-data-text='No data'
        placeholder='Enter English letters'

        virtual-list
        :keeps='15'
        :key-value="['label', 'value']"
        data-key='value'
        multiple
        @change='testChange1'
        @input='testInput1'
       :visible-change-keyword-cached="true"
       :visible-change-select-list-cached="true"
     >
      <template #option="{row}">
        <span v-if='row.value == 0'>
          <span style='color: red' >label: 《{{row.label}}》</span> - value: 《{{row.value}}》
        </span>
        <span style='color: blue' v-if='row.value == 1'>{{row.label}}</span>
        <span v-if='row.value != 0 && row.value != 1'>{{row.label}}</span>
      </template>
     </NfLazySelect>
  </div>
</div>

     <ElDivider class="select-demo-divider">Above: multiple selection </ElDivider>
     <ElDivider class="select-demo-divider">Below: single selection </ElDivider>

     <div class="select-demo">
  <div class="select-demo-result"><pre>{{ test1 }}</pre></div>
  <div class="select-demo-controls">
<NfLazySelect
        v-model="test1"

       :request="testPage"
        @change='testChange2'
        @input='testInput2'

        :visible-change-keyword-cached="true"
        :visible-change-select-list-cached="true"

        :page-size='10'
        keyword-alias="keyword"
        page-no-alias="pageNo"
        page-size-alias="pageSize"

        loading-desc='Loading...'
        no-data-text='No data'
        placeholder='Enter English letters'

        virtual-list
        :keeps='15'
        :key-value="['label', 'value']"
        data-key='value'
     />
  </div>
</div>


     <ElDivider class="select-demo-divider">Above: virtual scrolling enabled </ElDivider>
     <ElDivider class="select-demo-divider">Below: regular scrolling </ElDivider>

     <div class="select-demo">
  <div class="select-demo-result"><pre>{{ test2 }}</pre></div>
  <div class="select-demo-controls">
<NfLazySelect
        v-model="test2"
        @change='testChange3'
        @input='testInput3'

        :request="testPage"
        :pageSize='10'

        loading-desc='Loading...'
        no-data-text='No data'
        placeholder='Enter English letters'

        :key-value="['label', 'value']"
     >
      <template #option="{row}">
        <span v-if='row.value == 0'>
          <span style='color: red' >label: 《{{row.label}}》</span> - value: 《{{row.value}}》
        </span>
        <span style='color: blue' v-if='row.value == 1'>{{row.label}}</span>
        <span v-if='row.value != 0 && row.value != 1'>{{row.label}}</span>
      </template>
     </NfLazySelect>
  </div>
</div>
  </div>
  </NfConfigProvider>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { NfConfigProvider, NfLazySelect } from '@94ai-plus/common-ui'
import { ElDivider } from 'element-plus'

const test = ref();
const test1 = ref();
const test2 = ref();

const testChange1 = () => {
  console.log('testChange1')
}
const testChange2 = () => {
  console.log('testChange2')
}
const testChange3 = () => {
  console.log('testChange3')
}
const testInput1 = () => {
  console.log('testInput1')
}
const testInput2 = () => {
  console.log('testInput2')
}
const testInput3 = () => {
  console.log('testInput3')
}

// Mock paginated API; instances do not share request state.
const testPage = async (params) => {
  await new Promise(resolve => setTimeout(resolve, 150))
  const page = Number(params.pageNo || 1)
  const size = Number(params.pageSize || 10)
  const keyword = String(params.keyword || '')
  return {
    records: Array.from({ length: Math.min(size, 1000 - (page - 1) * size) }, (_, index) => {
      const value = String((page - 1) * size + index) + keyword
      return { value, label: value + '显示', a: 1 }
    }),
    total: 1000
  }
}
</script>

<style scoped>
.select-demo { display: flex; flex-direction: column; gap: 16px; max-width: 100%; }
.select-demo-result > pre { margin: 0; }
.select-demo-controls { display: flex; flex-direction: column; align-items: flex-start; gap: 16px; max-width: 100%; }
.select-demo-controls > * { max-width: 100%; }
.select-demo-divider { display: flex; align-items: center; gap: 12px; height: auto; border-top: 0; }
.select-demo-divider::before, .select-demo-divider::after { content: ''; flex: 1; min-width: 12px; border-top: 1px solid var(--el-border-color); }
.select-demo-divider :deep(.el-divider__text) { position: static; transform: none; flex: 0 1 auto; min-width: 0; max-width: calc(100% - 48px); padding: 0; text-align: center; white-space: normal; }
</style>
```

### Data echo {#example-2}

### Data echo
```vue
<template>
  <NfConfigProvider theme="chalk" locale="en-US">
<div>
    <div class="select-demo">
  <div class="select-demo-result"><pre>{{ test3 }}</pre></div>
  <div class="select-demo-controls">
<NfLazySelect
        v-model="test3"
        ref='lazy3'
        :request="testPageEcho3"
        :page-size='10'
        keyword-alias="keyword"
        page-no-alias="pageNo"
        page-size-alias="pageSize"
        @change='testChange4'
        @input='testInput4'

        loading-desc='Loading...'
        no-data-text='No data'
        placeholder='Enter English letters'

        virtual-list
        :keeps='15'
        :key-value="['label', 'value']"
        data-key='value'
        multiple
     />
  </div>
</div>

     <ElDivider class="select-demo-divider">Above: multiple selection </ElDivider>
     <ElDivider class="select-demo-divider">Below: single selection </ElDivider>

      <div class="select-demo">
  <div class="select-demo-result"><pre>{{ test4 }}</pre></div>
  <div class="select-demo-controls">
<NfLazySelect
        v-model="test4"
        ref='lazy4'
        :request="testPageEcho4"
        :page-size='10'
        keyword-alias="keyword"
        page-no-alias="pageNo"
        page-size-alias="pageSize"

        loading-desc='Loading...'
        no-data-text='No data'
        placeholder='Enter English letters'

        virtual-list
        :keeps='15'
        :key-value="['label', 'value']"
        data-key='value'
     />
  </div>
</div>

     <ElDivider class="select-demo-divider">Above: virtual scrolling enabled </ElDivider>
     <ElDivider class="select-demo-divider">Below: regular scrolling </ElDivider>

      <div class="select-demo">
  <div class="select-demo-result"><pre>{{ test5 }}</pre></div>
  <div class="select-demo-controls">
<NfLazySelect
        v-model="test5"
        ref='lazy5'
        :request="testPageEcho5"
        :page-size='10'
        keyword-alias="keyword"
        page-no-alias="pageNo"
        page-size-alias="pageSize"

        loading-desc='Loading...'
        no-data-text='No data'
        placeholder='Enter English letters'

        :key-value="['label', 'value']"
     />
  </div>
</div>

  </div>
  </NfConfigProvider>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { NfConfigProvider, NfLazySelect } from '@94ai-plus/common-ui'
import { ElDivider } from 'element-plus'

const initData3 = [
  {
    label: '0qwert回显',
    value: '0qwert'
  },
  {
    label: 'a回显',
    value: 'a'
  },
  {
    label: 'b回显',
    value: 'b'
  }
]
const test3 = ref([initData3[0].value, initData3[1].value, initData3[2].value]);

const initData4 = {
  label: '0qwert回显',
  value: '0qwert'
}
const test4 = ref(initData4.value);

const initData5 = {
  label: '0qwert回显',
  value: '0qwert'
}
const test5 = ref(initData5.value);

const testChange4 = () => {
  console.log('testChange4')
}
const testInput4 = () => {
  console.log('testInput4')
}

// Mock paginated API; instances do not share request state.
const testPage = async (params) => {
  await new Promise(resolve => setTimeout(resolve, 150))
  const page = Number(params.pageNo || 1)
  const size = Number(params.pageSize || 10)
  const keyword = String(params.keyword || '')
  return {
    records: Array.from({ length: Math.min(size, 1000 - (page - 1) * size) }, (_, index) => {
      const value = String((page - 1) * size + index) + keyword
      return { value, label: value + '显示', a: 1 }
    }),
    total: 1000
  }
}

// Return selected records together with the first page for the initial value request.
const testPageEcho = async (params, initial) => {
  const result = await testPage(params)
  if (Object.hasOwn(params, 'value') && params.value != null) {
    const selected = Array.isArray(initial) ? initial : [initial]
    const keys = new Set(selected.map(row => row.value))
    return { records: [...selected, ...result.records.filter(row => !keys.has(row.value))], total: result.total + selected.length }
  }
  return result
}

const testPageEcho3 = async (e) => await testPageEcho(e, initData3)
const testPageEcho4 = async (e) => await testPageEcho(e, initData4)
const testPageEcho5 = async (e) => await testPageEcho(e, initData5)
</script>

<style scoped>
.select-demo { display: flex; flex-direction: column; gap: 16px; max-width: 100%; }
.select-demo-result > pre { margin: 0; }
.select-demo-controls { display: flex; flex-direction: column; align-items: flex-start; gap: 16px; max-width: 100%; }
.select-demo-controls > * { max-width: 100%; }
.select-demo-divider { display: flex; align-items: center; gap: 12px; height: auto; border-top: 0; }
.select-demo-divider::before, .select-demo-divider::after { content: ''; flex: 1; min-width: 12px; border-top: 1px solid var(--el-border-color); }
.select-demo-divider :deep(.el-divider__text) { position: static; transform: none; flex: 0 1 auto; min-width: 0; max-width: calc(100% - 48px); padding: 0; text-align: center; white-space: normal; }
</style>
```

## Props {#props}

Descriptions preserve common-ui semantics; defaults and signatures follow the current Vue 3 implementation. Compatibility props do not enable unsupported legacy rendering.

| Attribute | Description | Type | Values | Default |
| --- | --- | --- | --- | --- |
| `modelValue / v-model (value)` | Bound value; value remains compatible; prefer v-model in Vue 3 | `SelectModelValue` | — | `undefined` |
| `emitSelectedItemOnClick` | get-selected-data returns values by default; true returns full records | `boolean` | — | `false` |
| `keyValue` | Fields used for option label and value | `[string, string]` | — | `['label', 'value']` |
| `virtualList` | Enable virtual scrolling | `boolean` | — | `false` |
| `dataKey` | Unique virtual row key: field name or function | `string \| ((row: SelectOption) => string \| number)` | — | `'templateId'` |
| `dataComponent` | Custom option component receiving source, index and extraProps | `Component` | — | `undefined` |
| `estimateSize` | Estimated row height in px | `number` | — | `34` |
| `keeps` | Minimum inline virtual window; dropdown virtualization is managed by SelectV2 | `number` | — | `30` |
| `pageSize` | Number of records per request | `number` | — | `10` |
| `keywordAlias` | Request field for search keyword | `string` | — | `'keyword'` |
| `pageNoAlias` | Request field for page number | `string` | — | `'pageNo'` |
| `pageSizeAlias` | Request field for page size | `string` | — | `'pageSize'` |
| `valueAlias` | Initial request field for selected values | `string` | — | `'value'` |
| `loadingDesc` | Loading message | `string` | — | `Locale configuration` |
| `showTip` | Show option tooltip | `boolean` | — | `true` |
| `multiple` | Enable multiple selection | `boolean` | — | `false` |
| `disabled` | Disable interaction | `boolean` | — | `Inherited configuration` |
| `allowEmptySearch` | Allow requests with an empty keyword | `boolean` | — | `true` |
| `size` | Input size; mini / medium map to small / default | `SelectSize` | `small / default / large / mini / medium` | `Inherited configuration` |
| `collapseTags` | Collapse selected tags in multiple mode | `boolean` | — | `multiple` |
| `multipleLimit` | Maximum selected items; 0 means unlimited | `number` | — | `0` |
| `placeholder` | Input placeholder | `string` | — | `Locale configuration` |
| `noDataText` | Empty list text; can use the empty slot | `string` | — | `Locale configuration` |
| `noDataImg` | Show NfEmpty when no data | `boolean` | — | `false` |
| `popperClass` | Dropdown CSS class | `string` | — | `undefined` |
| `popperAppendToBody` | Teleport dropdown to body; maps to Element Plus teleported | `boolean` | — | `true` |
| `start` | Initial inline scroll index | `number` | — | `0` |
| `offset` | Initial inline scroll offset in px | `number` | — | `0` |
| `direction` | Compatibility field; currently has no effect | `String` | `vertical` | `undefined` |
| `pageMode` | Compatibility field; currently has no effect | `boolean` | — | `undefined` |
| `topThreshold` | Top threshold for totop; may fire repeatedly | `number` | — | `0` |
| `bottomThreshold` | Bottom threshold for tobottom; may fire repeatedly | `number` | — | `0` |
| `rootTag` | Inline list root tag | `String` | — | `'div'` |
| `wrapTag` | Inline list wrapper tag | `String` | — | `'div'` |
| `wrapClass` | Compatibility field; currently has no effect | `String` | — | `undefined` |
| `wrapStyle` | Inline list wrapper style | `CSSProperties` | — | `undefined` |
| `itemTag` | Inline row wrapper tag | `String` | — | `'div'` |
| `itemClass` | Inline row CSS class | `String` | — | `undefined` |
| `itemClassAdd` | Extra row class function (index, row) | `(index: number, row: SelectOption) => string` | — | `undefined` |
| `itemStyle` | Inline row style | `CSSProperties` | — | `undefined` |
| `itemScopedSlots` | Compatibility field; currently has no effect | `Object` | — | `undefined` |
| `headerTag` | Compatibility field; currently has no effect | `String` | — | `undefined` |
| `headerClass` | Compatibility field; currently has no effect | `String` | — | `undefined` |
| `headerStyle` | Compatibility field; currently has no effect | `CSSProperties` | — | `undefined` |
| `footerTag` | Compatibility field; currently has no effect | `String` | — | `undefined` |
| `footerClass` | Compatibility field; currently has no effect | `String` | — | `undefined` |
| `footerStyle` | Compatibility field; currently has no effect | `CSSProperties` | — | `undefined` |
| `options` | List of selectable options | `SelectOption[]` | — | `[]` |
| `itemOptions` | Configure list properties and events together; event names accept kebab-case or camelCase | `Record<string, unknown>` | — | `{}` |
| `tag` | Custom rendering tag; div or custom-select-dropdown displays an inline list | `string \| Component` | — | `'el-select'` |
| `selectAll` | Show select-all control | `boolean` | — | `false` |
| `selectAllText` | Select-all label | `string` | — | `Locale configuration` |
| `clearable` | Show the clear selection control | `boolean` | — | `true` |
| `reserveKeyword` | Keep the search keyword after selection | `boolean` | — | `true` |
| `filterable` | Enable searching | `boolean` | — | `true` |
| `filterMethod` | Custom filtering function | `(query: string) => void \| Promise<void>` | — | `undefined` |
| `remote` | Use remote filtering | `boolean` | — | `false` |
| `loading` | Loading state | `boolean` | — | `false` |
| `defaultFirstOption` | Select the first match on Enter | `boolean` | — | `false` |
| `allowCreate` | Allow new options; requires filterable | `boolean` | — | `false` |
| `automaticDropdown` | Open non-filterable select on focus | `boolean` | — | `false` |
| `name` | Native input name | `string` | — | `undefined` |
| `keywordHighlight` | Highlight search keyword | `boolean` | — | `true` |
| `keywordLabelAlias` | Compatibility field; highlighting uses text nodes, without HTML injection | `string` | — | `'keywordHighlightLabel'` |
| `echoValueTop` | Move selected rows to top in virtual list | `boolean` | — | `true` |
| `width` | Selector width | `string` | — | `'100%'` |
| `maxWidth` | Maximum selector width | `string` | — | `undefined` |
| `height` | Scrollable list height | `string` | — | `'245px'` |
| `extraProps` | Extra props passed to custom option component | `Record<string, unknown>` | — | `undefined` |
| `headeClass` | Compatibility field; currently has no effect | `string` | — | `undefined` |
| `beforeVisibleChange` | Post-visibility hook; return break to skip subsequent internal handling | `(visible: boolean) => void \| "break" \| "discard-cache" \| Promise<void \| "break" \| "discard-cache">` | — | `undefined` |
| `placement` | Dropdown placement | `SelectProps["placement"]` | — | `undefined` |
| `request` | Paginated request returning records and total record count; parameters and context below | `LazySelectRequest` | — | `undefined` |
| `initList` | Load initially; false defers loading until focus | `boolean` | — | `true` |
| `initListAssigmentValue` | Compatibility prop; initial data does not overwrite the bound value | `boolean` | — | `false` |
| `visibleChangeKeywordCached` | Preserve keyword across closing and reopening | `boolean` | — | `false` |
| `visibleChangeSelectListCached` | Preserve searched list across closing and reopening | `boolean` | — | `false` |

request(params, context) accepts a synchronous result or Promise. params uses the aliases above for page, page size and keyword; initial echo also includes selected values (including 0 / false). context.data is the normalized list, originData the raw records and allCachedDataList the instance cache. Return total as record count, not page count. In fetch-data, current is the current page; records is the raw response, data the accumulated normalized list and originData the accumulated raw list.

```ts
type RequestParams = Record<string, string | number | boolean | (string | number | boolean)[] | undefined>
interface RequestContext {
  data: SelectOption[]
  originData: SelectOption[]
  allCachedDataList: SelectOption[]
}
type RequestResult = { records: SelectOption[]; total: number }
type LazySelectRequest = (params: RequestParams, context: RequestContext) => RequestResult | Promise<RequestResult>
interface FetchCallBackData {
  total: number
  current: number
  hasMore: boolean
  keyword: string
  records: SelectOption[]
  data: SelectOption[]
  originData: SelectOption[]
  allCachedDataList: SelectOption[]
}
```

## Events {#events}

| Event | Description | Arguments |
| --- | --- | --- |
| `update:modelValue` | Selection changed; update v-model | `(value: SelectModelValue)` |
| `update:value` | Selection changed; compatibility event | `(value: SelectModelValue)` |
| `input` | Selection changed; compatibility event | `(value: SelectModelValue)` |
| `change` | Fires when selection changes | `(value: SelectModelValue)` |
| `focus` | Input gains focus | `(event: FocusEvent)` |
| `blur` | Input loses focus | `(event: FocusEvent)` |
| `clear` | Clear control activated | `()` |
| `remove-tag` | Tag removed in multiple mode | `(value: SelectValue)` |
| `visible-change` | Dropdown shown: true; hidden: false | `(visible: boolean)` |
| `select-item` | Option clicked; returns its value | `(value: SelectValue)` |
| `scroll` | List scroll; Event only, without the old range argument | `(event: Event)` |
| `totop` | List reaches top threshold | `(event?: Event)` |
| `tobottom` | List reaches bottom threshold | `(event?: Event)` |
| `resized` | List viewport measurement | `(id: string \| number, size: number)` |
| `fetch-data` | After each successful request | `(data: FetchCallBackData)` |
| `fetch-error` | Request failed | `(error: unknown)` |
| `get-selected-data` | Selection data; emitSelectedItemOnClick chooses values or full records | `(valueOrRows: SelectModelValue \| SelectOption \| (SelectOption \| undefined)[])` |

## Slots {#slots}

| Slot | Description | Scope |
| --- | --- | --- |
| `default` | Below regular/inline list; use footer for virtual dropdown | — |
| `option` | Custom option content | `{ row: SelectOption, item: SelectOption, index: number }` |
| `header` | List header | — |
| `footer` | List footer | — |
| `prefix` | Input prefix | — |
| `empty` | Empty option list content | — |
| `loading` | Custom loading state | — |
| `tag` | Custom selected tags | `Element Plus tag slot props` |

## Exposed methods and state {#methods}

- `currentVal`
- `nfLazySelect`
- `hasMore`
- `keyword`
- `totalPage`
- `pageNo`
- `loading`
- `focusThrough`
- `initListFetch()`
- `focusFetchHandler(init?, forceRequest?)`
- `fetchHandler(params?, restart?, forceRequest?)`
- `clearHandler()`
- `handleSearch(keyword, matchKeywords?)`
- `visibleChange(boolean)`
- `cachedKeyword()`
- `loadMore()`
- `visibleIntersect`
- `allCachedDataList`
- `allCachedDataMap`
- `data`
- `originData`
- `open()`

## Migration notes {#migration}

Vue 3 uses `modelValue` / `update:modelValue`; legacy `value`, `update:value` and `input` remain available on selection components. The implementation uses public Element Plus APIs, not Element UI internals. `mini` maps to `small`; `medium` maps to `default`.

`request(params, context)` returns `{ records, total }`. Stale requests cannot overwrite the current search. `fetch-error` reports failures; retry the same page. `allCachedDataMap` / `dataMap` are typed Maps.
