物料搜索:el-select 重构为 el-autocomplete Regression 修复(value-key 缺失 + parentNameInput 未声明 + onChildClear 不完整)

This commit is contained in:
DXC
2026-06-05 11:02:35 +08:00
parent ff5418afa3
commit 355a21e94c
6 changed files with 263 additions and 733 deletions

View File

@ -69,35 +69,28 @@
<el-row :gutter="20">
<el-col :span="16">
<el-form-item label="父件 (成品)" prop="parent_id" v-if="hasFormFieldPermission('parent_id')">
<!-- ====== 改造:父件下拉 - 远程搜索 + 懒加载 ====== -->
<el-select
v-model="form.parent_id"
<!-- ====== 父件搜索 - el-autocomplete ====== -->
<el-autocomplete
v-model="parentNameInput"
:fetch-suggestions="fetchParentSuggestions"
:value-key="'name'"
clearable
placeholder="请搜索并选择父件"
filterable
remote
reserve-keyword="true"
:remote-method="(q: string) => handleRemoteSearch(q, 'parent')"
:loading="selectLoading"
:loading="searchLoading"
:trigger-on-focus="true"
style="width: 100%"
:disabled="isReadOnlyMode || isEditMode"
class="beautified-select"
popper-class="bom-loadmore-popper parent-popper"
default-first-option="true"
@visible-change="(visible: boolean) => handleVisibleChange(visible, 'parent')"
@change="onParentChange"
@select="onParentSelected"
@clear="onParentClear"
popper-class="bom-parent-popper"
>
<el-option
v-for="item in parentOptions"
:key="item.id"
:label="`${item.name} (${item.spec})`"
:value="item.id"
>
<template #default="{ item }">
<div class="option-row">
<span class="option-name">{{ item.name }}</span>
<span class="option-spec">{{ item.spec }}</span>
</div>
</el-option>
</el-select>
</template>
</el-autocomplete>
<el-link
v-if="form.parent_id && !isReadOnlyMode"
type="primary"
@ -166,41 +159,34 @@
<el-table :data="filteredChildren" border style="width: 100%; margin-bottom: 15px" max-height="300">
<el-table-column label="子件物料" min-width="250" v-if="hasFormFieldPermission('child_id')">
<template #default="{ row }">
<!-- ====== 改造:子件下拉 - 远程搜索 + 懒加载 ====== -->
<!-- ====== 子件搜索 - el-autocomplete,行级绑定 ====== -->
<div style="display: flex; align-items: center; gap: 8px;">
<el-select
v-model="row.child_id"
<el-autocomplete
v-model="row.material_name"
:fetch-suggestions="(q: string, cb: (results: any[]) => void) => fetchChildSuggestions(row, q, cb)"
:value-key="'name'"
clearable
placeholder="请搜索原料"
filterable
remote
reserve-keyword="true"
:loading="searchLoading"
:trigger-on-focus="true"
style="flex: 1;"
:remote-method="(q: string) => handleRemoteSearch(q, 'child', row.rowKey)"
:loading="selectLoading"
:loading-text="`正在加载第 ${childQueryParams.page} 页...`"
:popper-class="`bom-loadmore-popper child-popper-${row.rowKey}`"
:disabled="isReadOnlyMode"
default-first-option="true"
@visible-change="(visible: boolean) => handleVisibleChange(visible, 'child', row.rowKey)"
@select="(item: any) => onChildSelected(row, item)"
@clear="() => onChildClear(row)"
>
<el-option
v-for="item in getChildOptions(row.rowKey)"
:key="item.id"
:label="`${item.name} (${item.spec})`"
:value="item.id"
>
<template #default="{ item }">
<div class="option-row">
<span class="option-name">{{ item.name }}</span>
<span class="option-spec">{{ item.spec }}</span>
</div>
</el-option>
</el-select>
</template>
</el-autocomplete>
<el-tooltip content="前往修改基础信息" placement="top" v-if="row.child_id && !isReadOnlyMode">
<el-button
type="primary"
link
:icon="EditPen"
@click.stop="openMaterialInNewTab(row.child_id, getChildSpec(row.rowKey))"
@click.stop="openMaterialInNewTab(row.child_id, row.material_spec)"
style="font-size: 16px; padding: 4px;"
/>
</el-tooltip>
@ -249,7 +235,7 @@ import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { Plus, Search, EditPen } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getBomList, getBomDetail, saveBom, deleteBom } from '@/api/bom'
import { getMaterialBaseList } from '@/api/inbound/stock'
import { searchMaterialBase } from '@/api/inbound/buy'
import { useUserStore } from '@/stores/user'
// ============================================================
@ -271,6 +257,8 @@ interface MaterialBase {
interface ChildRow {
rowKey: number // 唯一标识,替代 $index 作为 Map key
child_id: number | null
material_name: string
material_spec: string
dosage: number
remark: string
}
@ -293,7 +281,17 @@ const activeCategories = ref([]) // 默认全部展开
const searchKeyword = ref('')
const childSearchKeyword = ref('')
// ★ 自动搜索:输入后 500ms 防抖触发搜索(无需回车)
const filteredChildren = computed(() => {
if (!childSearchKeyword.value) return form.children
const kw = childSearchKeyword.value.toLowerCase()
return form.children.filter(child => {
const name = (child.material_name || '').toLowerCase()
const spec = (child.material_spec || '').toLowerCase()
return name.includes(kw) || spec.includes(kw)
})
})
// 自动搜索:输入后 500ms 防抖触发搜索(无需回车)
watch(searchKeyword, (val) => {
// 防抖:延迟 500ms 执行,避免频繁请求
clearTimeout((window as any)._bomSearchTimer)
@ -303,257 +301,67 @@ watch(searchKeyword, (val) => {
})
// ============================================================
// 【改造】分页 + 远程搜索相关状态
// Material Search - el-autocomplete
// ============================================================
const PAGE_SIZE = 20
const searchLoading = ref(false)
const parentNameInput = ref('')
// 父件下拉
const parentOptions = ref<MaterialBase[]>([])
const parentQueryParams = reactive({ page: 1, limit: PAGE_SIZE, keyword: '' })
const parentHasMore = ref(true)
// 子件下拉(每行独立状态)
interface ChildDropdownState {
options: MaterialBase[]
queryParams: { page: number; limit: number; keyword: string }
hasMore: boolean
}
const childDropdownStates = ref<Map<number, ChildDropdownState>>(new Map())
// 子件下拉专用的查询参数(用于 loading-text 显示)
const childQueryParams = reactive({ page: 1 })
// 加载状态(父件和子件共用一个 loading,避免闪烁)
const selectLoading = ref(false)
const getChildOptions = (index: number): MaterialBase[] => {
return childDropdownStates.value.get(index)?.options ?? []
}
// ============================================================
// 【改造】获取物料列表(分页版本)
// ============================================================
const fetchMaterialOptions = async (
type: 'parent' | 'child',
rowKey?: number,
isLoadMore = false
) => {
// 子件行需要 rowKey(唯一标识,不再依赖数组索引)
if (type === 'child' && rowKey === undefined) return
const params = type === 'parent'
? parentQueryParams
: childDropdownStates.value.get(rowKey!)?.queryParams
if (!params) return
selectLoading.value = true
try {
const res = await getMaterialBaseList({
page: params.page,
limit: params.limit,
keyword: params.keyword
})
if (res.code === 200) {
const list: MaterialBase[] = res.data?.list ?? res.data ?? []
const total = res.data?.total ?? list.length
if (type === 'parent') {
if (isLoadMore) {
// 去重追加
const existingIds = new Set(parentOptions.value.map(m => m.id))
const newItems = list.filter(m => !existingIds.has(m.id))
parentOptions.value.push(...newItems)
} else {
// ★ 修复回显丢失:先检查当前选中项是否在列表中,不在则从原 options 保留
const selectedId = form.parent_id
let finalList = [...list]
if (selectedId && !list.find(m => m.id === selectedId)) {
const existing = parentOptions.value.find(m => m.id === selectedId)
if (existing) finalList.unshift(existing)
}
parentOptions.value = finalList
}
// 判断是否还有更多数据
parentHasMore.value = parentOptions.value.length < total
} else {
const state = childDropdownStates.value.get(rowKey!)
if (!state) return
if (isLoadMore) {
const existingIds = new Set(state.options.map(m => m.id))
const newItems = list.filter(m => !existingIds.has(m.id))
state.options.push(...newItems)
} else {
// ★ 修复回显丢失:先通过 rowKey 精准找到当前行,再检查选中项是否在列表中
const currentRow = form.children.find(c => c.rowKey === rowKey)
const currentSelectedId = currentRow?.child_id
let finalList = [...list]
if (currentSelectedId && !list.find(m => m.id === currentSelectedId)) {
const existing = state.options.find(m => m.id === currentSelectedId)
if (existing) finalList.unshift(existing)
}
state.options = finalList
}
state.hasMore = state.options.length < total
}
}
} catch (error) {
// 错误已由全局拦截器统一处理
} finally {
selectLoading.value = false
}
}
// ============================================================
// 【改造】远程搜索处理函数
// ============================================================
const handleRemoteSearch = (
query: string,
type: 'parent' | 'child',
rowKey?: number
) => {
// 防御性处理:粘贴场景常混入零宽字符 / 控制字符 / 不可见 Unicode
const fetchParentSuggestions = (query: string, cb: (results: any[]) => void) => {
const rawQuery = String(query || '')
const safeQuery = rawQuery.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF]/g, '').trim()
if (type === 'parent') {
parentQueryParams.keyword = safeQuery
parentQueryParams.page = 1
parentHasMore.value = true
fetchMaterialOptions('parent')
} else if (type === 'child' && rowKey !== undefined) {
const state = childDropdownStates.value.get(rowKey)
if (!state) return
state.queryParams.keyword = safeQuery
state.queryParams.page = 1
state.hasMore = true
fetchMaterialOptions('child', rowKey)
searchLoading.value = true
searchMaterialBase(safeQuery).then((res: any) => {
cb(res.data?.items || [])
}).catch(() => cb([])).finally(() => { searchLoading.value = false })
}
const onParentClear = () => {
form.parent_id = null
form.bom_no = ''
}
const onParentSelected = (item: any) => {
form.parent_id = item.id
if (item.spec) {
form.bom_no = item.spec.split('/')[0].trim()
} else {
form.bom_no = ''
}
}
// ============================================================
// 【改造】下拉框展开/收起处理(重置分页 + 预加载第一页)
// ============================================================
const handleVisibleChange = (visible: boolean, type: 'parent' | 'child', rowKey?: number) => {
if (!visible) return
const fetchChildSuggestions = (row: any, query: string, cb: (results: any[]) => void) => {
const rawQuery = String(query || '')
const safeQuery = rawQuery.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF]/g, '').trim()
searchLoading.value = true
searchMaterialBase(safeQuery).then((res: any) => {
cb(res.data?.items || [])
}).catch(() => cb([])).finally(() => { searchLoading.value = false })
}
if (type === 'parent') {
// 防御性拦截:竞态条件守卫
// 如果当前已经有搜索关键字(例如用户刚刚粘贴了内容、remote-method 已经设置了 keyword),
// 绝对不要去请求默认列表,否则会清空 keyword、覆盖正确结果。
if (parentQueryParams.keyword || parentOptions.value.length > 0) return
parentQueryParams.page = 1
parentQueryParams.keyword = ''
parentHasMore.value = true
fetchMaterialOptions('parent')
} else if (type === 'child' && rowKey !== undefined) {
// 确保该行下拉状态已初始化
if (!childDropdownStates.value.has(rowKey)) {
childDropdownStates.value.set(rowKey, {
options: [],
queryParams: { page: 1, limit: PAGE_SIZE, keyword: '' },
hasMore: true
})
}
const state = childDropdownStates.value.get(rowKey)!
// 防御性拦截:竞态条件守卫(同上)
if (state.queryParams.keyword || state.options.length > 0) return
state.queryParams.page = 1
state.queryParams.keyword = ''
state.hasMore = true
fetchMaterialOptions('child', rowKey)
const onChildClear = (row: any) => {
row.child_id = null
row.material_name = ''
row.material_spec = ''
row.dosage = 0
}
const onChildSelected = (row: any, item: any) => {
const existingIndex = form.children.findIndex((child, idx) => idx !== form.children.indexOf(row) && child.child_id === item.id)
if (existingIndex !== -1) {
ElMessage.warning(`该物料已在第 ${existingIndex + 1} 行存在,请合并用量或删除重复项`)
row.child_id = null
row.material_name = ''
row.dosage = 0
return
}
// 延迟 50ms 等待弹窗 DOM 完全渲染
setTimeout(() => {
// 动态拼接精确的选择器
const exactSelector = type === 'parent'
? '.parent-popper .el-select-dropdown__wrap'
: `.child-popper-${rowKey} .el-select-dropdown__wrap`;
const popperWrap = document.querySelector(exactSelector) as HTMLElement;
if (popperWrap) {
// 解绑旧事件,防止重复触发
if ((popperWrap as any)._scrollHandler) {
popperWrap.removeEventListener('scroll', (popperWrap as any)._scrollHandler);
}
// 定义滚动触发逻辑
(popperWrap as any)._scrollHandler = function() {
const { scrollTop, scrollHeight, clientHeight } = this;
// 距离底部 10px 触发
if (scrollHeight - scrollTop - clientHeight <= 10) {
if (type === 'parent') {
loadMoreParent();
} else if (type === 'child' && rowKey !== undefined) {
// 触发子件加载
loadMoreChild(popperWrap, rowKey);
}
}
};
popperWrap.addEventListener('scroll', (popperWrap as any)._scrollHandler);
}
}, 50);
row.child_id = item.id
row.material_name = item.name
row.material_spec = item.spec
row.dosage = 1
}
// ============================================================
// 【改造】滚动触底加载更多
// ============================================================
const loadMoreParent = () => {
if (selectLoading.value || !parentHasMore.value) return
parentQueryParams.page++
fetchMaterialOptions('parent', undefined, true)
}
const loadMoreChild = (_el: HTMLElement, rowKey: number) => {
const state = childDropdownStates.value.get(rowKey)
if (!state) return
if (selectLoading.value || !state.hasMore) return
state.queryParams.page++
fetchMaterialOptions('child', rowKey, true)
}
// ============================================================
// 【改造】初始化子件行下拉状态
// ============================================================
const initChildDropdownState = (rowKey: number) => {
if (!childDropdownStates.value.has(rowKey)) {
childDropdownStates.value.set(rowKey, {
options: [],
queryParams: { page: 1, limit: PAGE_SIZE, keyword: '' },
hasMore: true
})
}
}
// ============================================================
// 原有逻辑保留
// ============================================================
const filteredChildren = computed(() => {
if (!childSearchKeyword.value) {
return form.children
}
const kw = childSearchKeyword.value.toLowerCase()
return form.children.filter(child => {
const state = childDropdownStates.value.get(child.rowKey)
const material = state?.options.find(m => m.id === child.child_id)
if (!material) return false
const name = (material.name || '').toLowerCase()
const spec = (material.spec || '').toLowerCase()
return name.includes(kw) || spec.includes(kw)
})
})
// 获取子件规格(从 childDropdownStates 缓存中查找)
const getChildSpec = (rowKey: number): string => {
const state = childDropdownStates.value.get(rowKey)
const row = form.children.find(c => c.rowKey === rowKey)
if (!state || !row?.child_id) return ''
const material = state.options.find((m: MaterialBase) => m.id === row.child_id)
return material?.spec || ''
return row?.material_spec || ''
}
// 在新标签页打开基础信息编辑
@ -568,8 +376,7 @@ const openMaterialInNewTab = (targetId: number | null, keyword: string = '') =>
const openParentMaterial = () => {
if (!form.parent_id) return ElMessage.warning('请先选择父件')
const parent = parentOptions.value.find((p: MaterialBase) => p.id === form.parent_id)
const keyword = parent?.spec || parent?.name || ''
const keyword = parentNameInput.value || ''
openMaterialInNewTab(form.parent_id, keyword)
}
@ -660,14 +467,7 @@ const fetchBomList = async () => {
} finally { loading.value = false }
}
const onParentChange = (val: number) => {
const selected = parentOptions.value.find(m => m.id === val)
if (selected && selected.spec) {
form.bom_no = selected.spec.split('/')[0].trim()
} else {
form.bom_no = ''
}
}
const onParentChange = (val: number) => {}
const onChildChange = (val: number | null, index: number) => {
if (val !== null) {
@ -719,32 +519,18 @@ const handleSaveAs = async (row: BomItem) => {
})
}
// 4. 把"已清除 ID 的纯净数据"写入 form(保留子件下拉回显 + 父件下拉回显)
// 4. 把"已清除 ID 的纯净数据"写入 form
form.children = raw.children.map((child: any, idx: number) => ({
rowKey: idx,
child_id: child.child_id,
material_name: child.child_name || '未知物料',
material_spec: child.child_spec || '',
dosage: child.dosage,
remark: child.remark || ''
}))
form.children.forEach((child, idx) => {
initChildDropdownState(idx)
if (child.child_id) {
const state = childDropdownStates.value.get(idx)!
state.options = [{
id: raw.children[idx].child_id,
name: raw.children[idx].child_name || '未知物料',
spec: raw.children[idx].child_spec || ''
}]
state.hasMore = false
}
})
if (raw.parent_id) {
form.parent_id = raw.parent_id
parentOptions.value = [{
id: raw.parent_id,
name: raw.parent_name || '未知产品',
spec: raw.parent_spec || ''
}]
parentNameInput.value = raw.parent_name || '未知产品'
}
form.bom_no = (raw.parent_spec || row.bom_no).split('/')[0].trim()
form.remark = raw.remark || ''
@ -771,37 +557,17 @@ const loadDetail = async (bomNo: string, version: string) => {
const data = res.data
// 1. 映射子件基本数据(使用 idx 生成唯一 rowKey)
form.children = data.children.map((child: any, idx: number) => ({
rowKey: idx, // 用数组索引作为唯一标识(编辑场景下不会增删行)
rowKey: idx,
child_id: child.child_id,
material_name: child.child_name || '未知物料',
material_spec: child.child_spec || '',
dosage: child.dosage,
remark: child.remark || ''
}))
// 2. 初始化子件下拉状态,并预填充 options 解决回显显示 ID 的问题
form.children.forEach((child, idx) => {
initChildDropdownState(idx) // rowKey === idx(编辑场景下唯一)
if (child.child_id) {
const state = childDropdownStates.value.get(idx)!
// 从原始 data.children 中取对应的名称和规格注入 options
const rawChildData = data.children[idx]
state.options = [{
id: rawChildData.child_id,
name: rawChildData.child_name || '未知物料', // 依赖后端返回 child_name
spec: rawChildData.child_spec || '' // 依赖后端返回 child_spec
}]
state.hasMore = false
}
})
// 3. 处理父件回显,预填充 parentOptions
if (data.parent_id) {
form.parent_id = data.parent_id
parentOptions.value = [{
id: data.parent_id,
name: data.parent_name || '未知产品', // 依赖后端返回 parent_name
spec: data.parent_spec || '' // 依赖后端返回 parent_spec
}]
parentNameInput.value = data.parent_name || '未知产品'
}
if (data.parent_spec) {
@ -838,28 +604,18 @@ const resetForm = () => {
originalVersion = ''
currentBomNo = ''
childSearchKeyword.value = ''
// 重置子件下拉状态
childDropdownStates.value.clear()
// 重置父件下拉状态
parentOptions.value = []
parentQueryParams.page = 1
parentQueryParams.keyword = ''
parentHasMore.value = true
parentNameInput.value = ''
if (formRef.value) formRef.value.resetFields()
}
const addChild = () => {
const rowKey = Date.now() // 生成唯一标识,不再使用数组长度
form.children.push({ rowKey, child_id: null, dosage: 0, remark: '' })
initChildDropdownState(rowKey)
const rowKey = Date.now()
form.children.push({ rowKey, child_id: null, material_name: '', material_spec: '', dosage: 0, remark: '' })
}
const removeChild = (rowKey: number) => {
// 通过 rowKey 找到并删除该行(不再依赖数组索引)
const idx = form.children.findIndex(c => c.rowKey === rowKey)
if (idx !== -1) form.children.splice(idx, 1)
// 直接删除该行的下拉状态(无需重建索引)
childDropdownStates.value.delete(rowKey)
}
const submitForm = async () => {
@ -938,21 +694,13 @@ onMounted(() => {
// ★ 情况 B:还没建过BOM,打开新建并注入父件
handleCreate();
// 强行注入父件远程搜索选项
parentOptions.value = [{
id: parentId,
name: parentName,
spec: parentSpec
}];
parentNameInput.value = parentName;
// 给表单赋值
form.parent_id = parentId;
// 触发联动逻辑(自动带出版本和生成编号)
if (typeof onParentChange === 'function') {
setTimeout(() => {
onParentChange(parentId);
}, 100);
// 自动带出版本和生成编号
if (parentSpec) {
form.bom_no = parentSpec.split('/')[0].trim()
}
}
});