Files
pj_admin_cloud/src/components/Select/SelectMch.vue
T
2026-06-17 20:23:01 +08:00

109 lines
2.6 KiB
Vue

<template>
<el-select style="width: 100%" v-model="selectId" :placeholder="props.placeholder" clearable remote-show-suffix
filterable remote :disabled="props.disabled" :remote-method="remoteSearch" :loading="state.loading"
@visible-change="(e: boolean) => e && getOptions()" :multiple="props.multiple">
<el-option v-for="v in state.options" :key="v.id" :label="`${v.name}`" :value="v.id">
<div class="flex items-center">
<div class="color-primary">{{ v.name }}</div>
<div class="flex items-center justify-center ml5">
<el-tag size="small">
{{ v.deptName }}
</el-tag>
</div>
</div>
</el-option>
</el-select>
</template>
<script setup lang="ts" name="select-merchant">
import { reactive, onMounted, watch } from "vue" // 1. 添加 watch 导入
import * as mchApi from "/@/api/wallet/mch-manage"
const selectId = defineModel()
const props = withDefaults(
defineProps<{
placeholder?: string
apiParams?: any
autoFirst?: boolean
disabled?: boolean
multiple?: boolean
}>(),
{
placeholder: "请选择",
apiParams: {},
autoFirst: false,
disabled: false,
multiple: false
},
)
const queryForm = reactive<any>({
name: null,
current: 1,
size: 20,
})
const state = reactive<any>({
loading: true,
selectId: selectId.value,
options: [],
})
// 2. 修改 watch 逻辑
watch(
selectId,
(newVal, oldValue) => {
if (newVal == oldValue) return
state.selectId = newVal
// 如果有 newVal 且当前选项列表中没有这个 ID,则带上 ID 查询单条数据以显示 Label
if (newVal && !state.options.find((v: any) => v.id === newVal)) {
getOptions(newVal)
} else if (!newVal) {
getOptions()
}
},
{ immediate: true },
)
async function getOptions(id?: any) {
try {
state.loading = true
const _pa = {
...queryForm,
...props.apiParams,
}
// 3. 这里保留您提到的逻辑:如果有 id 参数,就加入搜索条件
if (id) {
_pa.id = id
}
const { data } = await mchApi.select(_pa)
state.options = data.records ?? []
if (props.autoFirst && state.options.length != 0) {
state.selectId = state.options[0].id
}
} finally {
setTimeout(() => (state.loading = false), 500)
}
}
function remoteSearch(params: string) {
if (params != queryForm.name) {
queryForm.name = params
// 搜索时会自动调用不带 id 的 getOptions,从而去掉 id 过滤
getOptions()
}
}
function clear() {
state.selectId = null
getOptions()
}
onMounted(() => {
// 如果没有初始 ID 且开启了 autoFirst,才执行默认查询
if (!selectId.value && props.autoFirst) {
getOptions()
}
})
</script>