<template> <div class="app-container"> <!-- 搜索条件 --> <el-form :model="queryParams"…
- Usercode
- Assistant
- User
- Assistant
- User
给我修改后完整的代码
- Assistant
- User
还是没有显示下拉框,让我输入,输入了又显示无数据,我想做成这样
- Assistant
你现在想要的是非远程搜索,直接加载完整列表用于下拉框选择,也就是说:
- User
给我完整的代码
- Assistant
给我修改后完整的代码
还是没有显示下拉框,让我输入,输入了又显示无数据,我想做成这样
你现在想要的是非远程搜索,直接加载完整列表用于下拉框选择,也就是说:
给我完整的代码
<el-form-item label="厂家" prop="factoryId">
<el-select
v-model="queryParams.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 180px"
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="生产日期" prop="productionDate">
<el-date-picker
clearable
v-model="queryParams.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 130px"
></el-date-picker>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod">
<el-input
v-model="queryParams.validityPeriod"
placeholder="请输入保质期"
clearable
style="width: 100px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="进货单" prop="purchaseId">
<el-select
v-model="queryParams.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 180px"
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="handleQuery"
>
搜索
</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
重置
</el-button>
</el-form-item>
</el-form>
<!-- 操作按钮 -->
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['pill:warning:add']"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['pill:warning:export']"
>
导出
</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
</el-row>
<!-- 表格 -->
<el-table
v-loading="loading"
:data="warningList"
@selection-change="handleSelectionChange"
style="width: 100%"
border
size="small"
>
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键ID" align="center" prop="warningId" width="90" />
<el-table-column label="药品名称" align="center" prop="drugName" width="150" />
<el-table-column label="生产厂家" align="center" prop="factoryName" width="180" />
<el-table-column
label="药品生产日期"
align="center"
prop="productionDate"
width="140"
>
<template #default="{ row }">
<span>{{ parseTime(row.productionDate, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column
label="保质期(天)"
align="center"
prop="validityPeriod"
width="100"
/>
<el-table-column
label="进货时间"
align="center"
prop="purchaseTime"
width="180"
>
<template #default="{ row }">
<span>{{ parseTime(row.purchaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="距离过期天数" align="center" width="120">
<template #default="{ row }">
<span>{{ getRemainingDays(row.productionDate, row.validityPeriod) }}</span>
</template>
</el-table-column>
<el-table-column label="库存数量" align="center" prop="stock" width="100" />
<el-table-column
label="操作"
align="center"
class-name="small-padding fixed-width"
width="120"
>
<template #default="{ row }">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(row)"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(row)"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<pagination
v-show="total > 0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 弹窗-添加或修改 -->
<el-dialog
:title="title"
:visible.sync="open"
width="500px"
append-to-body
@close="cancel"
>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="药品ID" prop="drugId" required>
<el-select
v-model="form.drugId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择药品"
:remote-method="fetchDrugOptions"
:loading="drugLoading"
style="width: 100%"
>
<el-option
v-for="item in drugOptions"
:key="item.drug_id"
:label="item.drug_name"
:value="item.drug_id"
/>
</el-select>
</el-form-item>
<el-form-item label="厂家ID" prop="factoryId" required>
<el-select
v-model="form.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 100%"
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="药品生产日期" prop="productionDate" required>
<el-date-picker
clearable
v-model="form.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod" required>
<el-input
v-model.number="form.validityPeriod"
placeholder="请输入保质期"
style="width: 100%"
type="number"
min="0"
/>
</el-form-item>
<el-form-item label="进货单ID" prop="purchaseId" required>
<el-select
v-model="form.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 100%"
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item label="库存数量">
<el-input
v-model="stockDisplay"
disabled
placeholder="自动获取库存数量"
/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
import request from '@/utils/request'
// 查询药品有效期预警,用于监控药品保质期列表 export function listWarning(query) { return request({ url: '/pill/warning/list', method: 'get', params: query }) }
// 查询药品有效期预警,用于监控药品保质期详细 export function getWarning(warningId) { return request({ url: '/pill/warning/' + warningId, method: 'get' }) }
// 新增药品有效期预警,用于监控药品保质期 export function addWarning(data) { return request({ url: '/pill/warning', method: 'post', data: data }) }
// 修改药品有效期预警,用于监控药品保质期 export function updateWarning(data) { return request({ url: '/pill/warning', method: 'put', data: data }) }
// 删除药品有效期预警,用于监控药品保质期 export function delWarning(warningId) { return request({ url: '/pill/warning/' + warningId, method: 'delete' }) }
<resultMap id="PillExpiryWarningResult" type="com.ruoyi.pill.domain.PillExpiryWarning">
<result property="warningId" column="warning_id" />
<result property="drugId" column="drug_id" />
<result property="factoryId" column="factory_id" />
<result property="productionDate" column="production_date" />
<result property="validityPeriod" column="validity_period" />
<result property="purchaseId" column="purchase_id" />
<result property="stock" column="stock" />
<result property="createTime" column="create_time" />
<result property="drugName" column="drug_name"/>
<result property="factoryName" column="factory_name"/>
<result property="purchaseTime" column="purchase_time"/>
<result property="daysToExpire" column="days_to_expire"/>
</resultMap>
<sql id="BaseSelectSql">
select
pe.warning_id,
pe.drug_id,
pe.factory_id,
pe.production_date,
pe.validity_period,
pe.purchase_id,
pd.num as stock,
pe.create_time,
pd.drug_name,
pf.factory_name,
pp.purchase_time,
datediff(date_add(pe.production_date, interval pe.validity_period day), curdate()) as days_to_expire
from pill_expiry_warning pe
LEFT JOIN pill_drug pd ON pe.drug_id = pd.drug_id
LEFT JOIN pill_factory pf ON pe.factory_id = pf.factory_id
LEFT JOIN pill_purchase pp ON pe.purchase_id = pp.purchase_id
</sql>
<select id="selectPillExpiryWarningList" parameterType="com.ruoyi.pill.domain.PillExpiryWarning" resultMap="PillExpiryWarningResult">
<include refid="BaseSelectSql"/>
<where>
<if test="drugId != null "> and pe.drug_id = #{drugId}</if>
<if test="factoryId != null "> and pe.factory_id = #{factoryId}</if>
<if test="productionDate != null "> and pe.production_date = #{productionDate}</if>
<if test="validityPeriod != null "> and pe.validity_period = #{validityPeriod}</if>
<if test="purchaseId != null "> and pe.purchase_id = #{purchaseId}</if>
</where>
</select>
<select id="selectPillExpiryWarningByWarningId" parameterType="Long" resultMap="PillExpiryWarningResult">
<include refid="BaseSelectSql"/>
where pe.warning_id = #{warningId}
</select>
<insert id="insertPillExpiryWarning" parameterType="com.ruoyi.pill.domain.PillExpiryWarning" useGeneratedKeys="true" keyProperty="warningId">
insert into pill_expiry_warning
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="drugId != null">drug_id,</if>
<if test="factoryId != null">factory_id,</if>
<if test="productionDate != null">production_date,</if>
<if test="validityPeriod != null">validity_period,</if>
<if test="purchaseId != null">purchase_id,</if>
<if test="stock != null">stock,</if>
<if test="createTime != null">create_time,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="drugId != null">#{drugId},</if>
<if test="factoryId != null">#{factoryId},</if>
<if test="productionDate != null">#{productionDate},</if>
<if test="validityPeriod != null">#{validityPeriod},</if>
<if test="purchaseId != null">#{purchaseId},</if>
<if test="stock != null">#{stock},</if>
<if test="createTime != null">#{createTime},</if>
</trim>
</insert>
<update id="updatePillExpiryWarning" parameterType="com.ruoyi.pill.domain.PillExpiryWarning">
update pill_expiry_warning
<set>
<if test="drugId != null">drug_id = #{drugId},</if>
<if test="factoryId != null">factory_id = #{factoryId},</if>
<if test="productionDate != null">production_date = #{productionDate},</if>
<if test="validityPeriod != null">validity_period = #{validityPeriod},</if>
<if test="purchaseId != null">purchase_id = #{purchaseId},</if>
<if test="stock != null">stock = #{stock},</if>
<if test="createTime != null">create_time = #{createTime},</if>
</set>
where warning_id = #{warningId}
</update>
<delete id="deletePillExpiryWarningByWarningId" parameterType="Long">
delete from pill_expiry_warning where warning_id = #{warningId}
</delete>
<delete id="deletePillExpiryWarningByWarningIds" parameterType="Long[]">
delete from pill_expiry_warning where warning_id in
<foreach item="warningId" collection="array" open="(" separator="," close=")">
#{warningId}
</foreach>
</delete>
前端新增的药品id,厂家id,进货单id没办法获取数据,进行下拉框选择
你提到前端新增的药品id,厂家id,进货单id没办法获取数据进行下拉框选择,一般原因和排查方向:
remote-method 函数未正确调用或返回了空数据。当前远程搜索方法:
async fetchDrugOptions(query) {
if (!query) {
this.drugOptions = []
return
}
this.drugLoading = true
try {
const res = await listDrugs({ drugName: query, pageNum: 1, pageSize: 20 })
this.drugOptions = res.rows || []
} catch (error) {
this.drugOptions = []
}
this.drugLoading = false
},
query 为空字符串的时候直接清空选项,并不去请求,导致选择框打开时没数据。async fetchDrugOptions(query = '') {
this.drugLoading = true
try {
const res = await listDrugs({ drugName: query, pageNum: 1, pageSize: 20 })
this.drugOptions = res.rows || []
} catch (error) {
this.drugOptions = []
}
this.drugLoading = false
},
原因:这样在输入为空时,也会加载初始数据,打开弹窗、搜索框也能显示。
同理,fetchFactoryOptions、fetchPurchaseOptions也做相同修改:
async fetchFactoryOptions(query = '') {
this.factoryLoading = true
try {
const res = await listFactories({ factoryName: query, pageNum: 1, pageSize: 20 })
this.factoryOptions = res.rows || []
} catch (error) {
this.factoryOptions = []
}
this.factoryLoading = false
},
async fetchPurchaseOptions(query = '') {
this.purchaseLoading = true
try {
const res = await listPurchases({ purchaseId: query, pageNum: 1, pageSize: 20 })
this.purchaseOptions = res.rows || []
} catch (error) {
this.purchaseOptions = []
}
this.purchaseLoading = false
},
当前handleAdd中重置form字段并打开弹窗,但未触发远程搜索拿到默认数据:
handleAdd() {
this.reset()
this.open = true
this.title = "添加药品有效期预警,用于监控药品保质期"
}
建议新增时,调用远程列表接口加载默认选项:
handleAdd() {
this.reset()
this.open = true
this.title = "添加药品有效期预警,用于监控药品保质期"
// 预加载前三个下拉框数据,传空字符串获取默认前20条
this.fetchDrugOptions()
this.fetchFactoryOptions()
this.fetchPurchaseOptions()
}
这样用户打开新增弹框时就有下拉选项,而不是空列表。
listDrugs、listFactories、listPurchases 能根据空字符串返回前20条数据如果后端接口无法在空字符串查询时返回数据,也需要调整后端逻辑,支持空查询参数时返回全部/前20条数据。
el-select的如下配置remote + filterable + reserve-keyword + clearable 模式,建议添加default-first-option,以便有默认选中项:
<el-select
...
default-first-option
@clear="onClear" <!-- 如有处理清空逻辑 -->
/>
drugOptions列表中,drug_id、drug_name字段名和接口是否匹配;同理factory和purchasefetchDrugOptions等函数是否执行。如果你新增时,手动赋值表单字段(例如form.drugId = xxx),确保对应下拉选项列表里有对应的值,否则会显示空。
如果drugOptions列表中没有这个drugId对应的option,这个值即使绑定了,也不会正常显示label,建议:
fetchDrugOptions增加条件或调用新接口查询单个药品详情,当修改表单时确保列表中有对应option选项。drugOptions,允许push新选项。你将:
query为空时不请求,改成默认也请求加载默认列表。如果你需要,我可以帮你写一份修改后的完整远程搜索方法和新增弹窗打开逻辑示例。
<el-form-item label="厂家" prop="factoryId">
<el-select
v-model="queryParams.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 180px"
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="生产日期" prop="productionDate">
<el-date-picker
clearable
v-model="queryParams.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 130px"
></el-date-picker>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod">
<el-input
v-model="queryParams.validityPeriod"
placeholder="请输入保质期"
clearable
style="width: 100px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="进货单" prop="purchaseId">
<el-select
v-model="queryParams.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 180px"
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="handleQuery"
>
搜索
</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
重置
</el-button>
</el-form-item>
</el-form>
<!-- 操作按钮 -->
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['pill:warning:add']"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['pill:warning:export']"
>
导出
</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
</el-row>
<!-- 表格 -->
<el-table
v-loading="loading"
:data="warningList"
@selection-change="handleSelectionChange"
style="width: 100%"
border
size="small"
>
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键ID" align="center" prop="warningId" width="90" />
<el-table-column label="药品名称" align="center" prop="drugName" width="150" />
<el-table-column label="生产厂家" align="center" prop="factoryName" width="180" />
<el-table-column
label="药品生产日期"
align="center"
prop="productionDate"
width="140"
>
<template #default="{ row }">
<span>{{ parseTime(row.productionDate, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column
label="保质期(天)"
align="center"
prop="validityPeriod"
width="100"
/>
<el-table-column
label="进货时间"
align="center"
prop="purchaseTime"
width="180"
>
<template #default="{ row }">
<span>{{ parseTime(row.purchaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="距离过期天数" align="center" width="120">
<template #default="{ row }">
<span>{{ getRemainingDays(row.productionDate, row.validityPeriod) }}</span>
</template>
</el-table-column>
<el-table-column label="库存数量" align="center" prop="stock" width="100" />
<el-table-column
label="操作"
align="center"
class-name="small-padding fixed-width"
width="120"
>
<template #default="{ row }">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(row)"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(row)"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<pagination
v-show="total > 0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 弹窗-添加或修改 -->
<el-dialog
:title="title"
:visible.sync="open"
width="500px"
append-to-body
@close="cancel"
>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="药品ID" prop="drugId" required>
<el-select
v-model="form.drugId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择药品"
:remote-method="fetchDrugOptions"
:loading="drugLoading"
style="width: 100%"
>
<el-option
v-for="item in drugOptions"
:key="item.drug_id"
:label="item.drug_name"
:value="item.drug_id"
/>
</el-select>
</el-form-item>
<el-form-item label="厂家ID" prop="factoryId" required>
<el-select
v-model="form.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 100%"
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="药品生产日期" prop="productionDate" required>
<el-date-picker
clearable
v-model="form.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod" required>
<el-input
v-model.number="form.validityPeriod"
placeholder="请输入保质期"
style="width: 100%"
type="number"
min="0"
/>
</el-form-item>
<el-form-item label="进货单ID" prop="purchaseId" required>
<el-select
v-model="form.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 100%"
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item label="库存数量">
<el-input
v-model="stockDisplay"
disabled
placeholder="自动获取库存数量"
/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
import request from '@/utils/request'
// 查询药品有效期预警,用于监控药品保质期列表 export function listWarning(query) { return request({ url: '/pill/warning/list', method: 'get', params: query }) }
// 查询药品有效期预警,用于监控药品保质期详细 export function getWarning(warningId) { return request({ url: '/pill/warning/' + warningId, method: 'get' }) }
// 新增药品有效期预警,用于监控药品保质期 export function addWarning(data) { return request({ url: '/pill/warning', method: 'post', data: data }) }
// 修改药品有效期预警,用于监控药品保质期 export function updateWarning(data) { return request({ url: '/pill/warning', method: 'put', data: data }) }
// 删除药品有效期预警,用于监控药品保质期 export function delWarning(warningId) { return request({ url: '/pill/warning/' + warningId, method: 'delete' }) }
package com.ruoyi.web.controller.pill;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.pill.domain.PillExpiryWarning; import com.ruoyi.pill.service.IPillExpiryWarningService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse; import java.util.List;
/**
药品有效期预警,用于监控药品保质期Controller
@author wuweiqiang
@date 2025-05-20 */ @RestController @RequestMapping("/pill/warning") public class PillExpiryWarningController extends BaseController { @Autowired private IPillExpiryWarningService pillExpiryWarningService;
/**
/**
/**
/**
/**
/**
import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity;
/**
药品有效期预警,用于监控药品保质期对象 pill_expiry_warning
@author wuweiqiang
@date 2025-05-20 */ public class PillExpiryWarning extends BaseEntity { private static final long serialVersionUID = 1L;
/** 主键ID */ private Long warningId;
/** 药品ID(关联pill_drug.drug_id) */ @Excel(name = "药品ID", readConverterExp = "关=联pill_drug.drug_id") private Long drugId;
/** 厂家ID(关联pill_factory.factory_id) */ @Excel(name = "厂家ID", readConverterExp = "关=联pill_factory.factory_id") private Long factoryId;
/** 药品生产日期 */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "药品生产日期", width = 30, dateFormat = "yyyy-MM-dd") private Date productionDate;
/** 保质期(天) */ @Excel(name = "保质期", readConverterExp = "天=") private Long validityPeriod;
/** 进货单ID(关联pill_purchase.purchase_id) */ @Excel(name = "进货单ID", readConverterExp = "关=联pill_purchase.purchase_id") private Long purchaseId;
/** 库存数量 */ @Excel(name = "库存数量") private Long stock;
/** 药品名称(来自pill_drug) */ @Excel(name = "药品名称") private String drugName;
/** 厂家名称(来自pill_factory) */ @Excel(name = "生产厂家") private String factoryName;
/** 进货时间(来自pill_purchase) */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "进货时间", width = 30, dateFormat = "yyyy-MM-dd") private Date purchaseTime;
/** 距离过期天数 */ @Excel(name = "距离过期天数") private Long daysToExpire;
public void setWarningId(Long warningId) { this.warningId = warningId; }
public Long getWarningId() { return warningId; }
public void setDrugId(Long drugId) { this.drugId = drugId; }
public Long getDrugId() { return drugId; }
public void setFactoryId(Long factoryId) { this.factoryId = factoryId; }
public Long getFactoryId() { return factoryId; }
public void setProductionDate(Date productionDate) { this.productionDate = productionDate; }
public Date getProductionDate() { return productionDate; }
public void setValidityPeriod(Long validityPeriod) { this.validityPeriod = validityPeriod; }
public Long getValidityPeriod() { return validityPeriod; }
public void setPurchaseId(Long purchaseId) { this.purchaseId = purchaseId; }
public Long getPurchaseId() { return purchaseId; }
public void setStock(Long stock) { this.stock = stock; }
public Long getStock() { return stock; }
public String getDrugName() { return drugName; }
public void setDrugName(String drugName) { this.drugName = drugName; }
public String getFactoryName() { return factoryName; }
public void setFactoryName(String factoryName) { this.factoryName = factoryName; }
public Date getPurchaseTime() { return purchaseTime; }
import java.util.List; import com.ruoyi.pill.domain.PillExpiryWarning;
/**
药品有效期预警,用于监控药品保质期Mapper接口
@author wuweiqiang
@date 2025-05-20 / public interface PillExpiryWarningMapper { /*
/**
/**
/**
/**
/**
import java.util.List; import com.ruoyi.common.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.pill.mapper.PillExpiryWarningMapper; import com.ruoyi.pill.domain.PillExpiryWarning; import com.ruoyi.pill.service.IPillExpiryWarningService;
/**
药品有效期预警,用于监控药品保质期Service业务层处理
@author wuweiqiang
@date 2025-05-20 */ @Service public class PillExpiryWarningServiceImpl implements IPillExpiryWarningService { @Autowired private PillExpiryWarningMapper pillExpiryWarningMapper;
/**
/**
/**
/**
/**
/**
import java.util.List; import com.ruoyi.pill.domain.PillExpiryWarning;
/**
药品有效期预警,用于监控药品保质期Service接口
@author wuweiqiang
@date 2025-05-20 / public interface IPillExpiryWarningService { /*
/**
/**
/**
/**
/**
前端新增的药品id,厂家id,进货单id没办法获取数据,进行下拉框选择
你好!你说“前端新增的药品id,厂家id,进货单id没办法获取数据,进行下拉框选择”,结合你贴的代码,这类问题典型是:
remote-method 未在空查询时请求数据,导致下拉项初始是空的,新增时无法选;你当前写法:
async fetchDrugOptions(query) {
if (!query) {
this.drugOptions = []
return
}
// ...调用接口
}
如果 query 空,就不请求了,导致用户打开选择框不输入任何字符无法加载数据。
改为:
async fetchDrugOptions(query = '') {
this.drugLoading = true;
try {
const res = await listDrugs({ drugName: query, pageNum: 1, pageSize: 20 });
this.drugOptions = res.rows || [];
} catch (error) {
this.drugOptions = [];
}
this.drugLoading = false;
}
同理 fetchFactoryOptions 和 fetchPurchaseOptions 也像上面一样,默认query = ''并请求服务。
这样一打开下拉框就可以加载初始数据,不需要输入关键字才有数据。
新增弹窗目前handleAdd没有加载下拉数据:
handleAdd() {
this.reset();
this.open = true;
this.title = "添加药品有效期预警,用于监控药品保质期";
}
应当调用远程加载函数,保证弹窗打开时有选项:
handleAdd() {
this.reset();
this.open = true;
this.title = "添加药品有效期预警,用于监控药品保质期";
this.fetchDrugOptions(); // 不传参数默认加载20条
this.fetchFactoryOptions();
this.fetchPurchaseOptions();
}
接口示例:
listDrugs({ drugName: '', pageNum: 1, pageSize: 20 })
listFactories({ factoryName: '', pageNum: 1, pageSize: 20 })
listPurchases({ purchaseId: '', pageNum: 1, pageSize: 20 })
如果你的后端接口收到空字符串时不返回数据,需要后端做调整,允许空查询参数时返回最近20条或默认数据。
el-select组件使用了filterable remote clearable reserve-keyword,这很好,远程搜索正常触发。el-select加入default-first-option属性,方便选择第一个选项(可选)。如果你编辑时选中一个 drugId,但它不在drugOptions里,预览显示会空。
解决办法:
drugOptions里,让它能正确显示label。handleUpdate时,在赋值form之后调用:async handleUpdate(row) {
this.reset();
const warningId = row?.warningId || this.ids[0];
const response = await getWarning(warningId);
this.form = response.data;
this.open = true;
this.title = "修改药品有效期预警,用于监控药品保质期";
// 确保下拉列表中含有当前已选项,方便显示label
await this.fetchDrugOptions('');
if (!this.drugOptions.find(d => d.drug_id === this.form.drugId)) {
const res = await listDrugs({ drugId: this.form.drugId, pageNum: 1, pageSize: 1 });
if (res.rows.length) this.drugOptions.push(res.rows[0]);
}
await this.fetchFactoryOptions('');
if (!this.factoryOptions.find(f => f.factory_id === this.form.factoryId)) {
// 类似查询单个厂家接口逻辑
}
await this.fetchPurchaseOptions('');
if (!this.purchaseOptions.find(p => p.purchase_id === this.form.purchaseId)) {
// 类似查询单个进货单接口逻辑
}
// 更新库存显示
this.updateStockDisplay();
}
async fetchDrugOptions(query = '') {
this.drugLoading = true;
try {
const res = await listDrugs({ drugName: query, pageNum: 1, pageSize: 20 });
this.drugOptions = res.rows || [];
} catch (error) {
this.drugOptions = [];
}
this.drugLoading = false;
},
async fetchFactoryOptions(query = '') {
this.factoryLoading = true;
try {
const res = await listFactories({ factoryName: query, pageNum: 1, pageSize: 20 });
this.factoryOptions = res.rows || [];
} catch (error) {
this.factoryOptions = [];
}
this.factoryLoading = false;
},
async fetchPurchaseOptions(query = '') {
this.purchaseLoading = true;
try {
const res = await listPurchases({ purchaseId: query, pageNum: 1, pageSize: 20 });
this.purchaseOptions = res.rows || [];
} catch (error) {
this.purchaseOptions = [];
}
this.purchaseLoading = false;
},
handleAdd() {
this.reset();
this.open = true;
this.title = "添加药品有效期预警,用于监控药品保质期";
this.fetchDrugOptions();
this.fetchFactoryOptions();
this.fetchPurchaseOptions();
},
这样你的弹窗新增和修改药品/厂家/进货单的下拉选择才能正常显示和选中。
如果需要我也可以帮你写对应的后端接口建议或者调试方法。你有任何问题随时问。
好的,下面给你整理一份修改后完整的Vue组件代码,重点是远程搜索方法默认加载数据,新增弹窗打开时预先加载下拉数据,修改弹窗时确保对应选项存在,下方添加了注释方便理解。
请结合你的业务真实接口适当调整。
<template>
<div class="app-container">
<!-- 搜索条件 -->
<el-form
:model="queryParams"
ref="queryForm"
size="small"
:inline="true"
v-show="showSearch"
label-width="68px"
>
<el-form-item label="药品" prop="drugId">
<el-select
v-model="queryParams.drugId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择药品"
:remote-method="fetchDrugOptions"
:loading="drugLoading"
style="width: 160px"
default-first-option
>
<el-option
v-for="item in drugOptions"
:key="item.drug_id"
:label="item.drug_name"
:value="item.drug_id"
/>
</el-select>
</el-form-item>
<el-form-item label="厂家" prop="factoryId">
<el-select
v-model="queryParams.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 180px"
default-first-option
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="生产日期" prop="productionDate">
<el-date-picker
clearable
v-model="queryParams.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 130px"
/>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod">
<el-input
v-model="queryParams.validityPeriod"
placeholder="请输入保质期"
clearable
style="width: 100px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="进货单" prop="purchaseId">
<el-select
v-model="queryParams.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 180px"
default-first-option
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="handleQuery"
>
搜索
</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
重置
</el-button>
</el-form-item>
</el-form>
<!-- 操作按钮 -->
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['pill:warning:add']"
>
新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['pill:warning:export']"
>
导出
</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
</el-row>
<!-- 表格 -->
<el-table
v-loading="loading"
:data="warningList"
@selection-change="handleSelectionChange"
style="width: 100%"
border
size="small"
>
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键ID" align="center" prop="warningId" width="90" />
<el-table-column label="药品名称" align="center" prop="drugName" width="150" />
<el-table-column label="生产厂家" align="center" prop="factoryName" width="180" />
<el-table-column
label="药品生产日期"
align="center"
prop="productionDate"
width="140"
>
<template #default="{ row }">
<span>{{ parseTime(row.productionDate, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column
label="保质期(天)"
align="center"
prop="validityPeriod"
width="100"
/>
<el-table-column
label="进货时间"
align="center"
prop="purchaseTime"
width="180"
>
<template #default="{ row }">
<span>{{ parseTime(row.purchaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="距离过期天数" align="center" width="120">
<template #default="{ row }">
<span>{{ getRemainingDays(row.productionDate, row.validityPeriod) }}</span>
</template>
</el-table-column>
<el-table-column label="库存数量" align="center" prop="stock" width="100" />
<el-table-column
label="操作"
align="center"
class-name="small-padding fixed-width"
width="120"
>
<template #default="{ row }">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(row)"
v-hasPermi="['pill:warning:edit']"
>
修改
</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(row)"
v-hasPermi="['pill:warning:remove']"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<pagination
v-show="total > 0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 弹窗-添加或修改 -->
<el-dialog
:title="title"
:visible.sync="open"
width="500px"
append-to-body
@close="cancel"
>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="药品ID" prop="drugId" required>
<el-select
v-model="form.drugId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择药品"
:remote-method="fetchDrugOptions"
:loading="drugLoading"
style="width: 100%"
default-first-option
>
<el-option
v-for="item in drugOptions"
:key="item.drug_id"
:label="item.drug_name"
:value="item.drug_id"
/>
</el-select>
</el-form-item>
<el-form-item label="厂家ID" prop="factoryId" required>
<el-select
v-model="form.factoryId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择厂家"
:remote-method="fetchFactoryOptions"
:loading="factoryLoading"
style="width: 100%"
default-first-option
>
<el-option
v-for="item in factoryOptions"
:key="item.factory_id"
:label="item.factory_name"
:value="item.factory_id"
/>
</el-select>
</el-form-item>
<el-form-item label="药品生产日期" prop="productionDate" required>
<el-date-picker
clearable
v-model="form.productionDate"
type="date"
value-format="yyyy-MM-dd"
placeholder="请选择生产日期"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod" required>
<el-input
v-model.number="form.validityPeriod"
placeholder="请输入保质期"
style="width: 100%"
type="number"
min="0"
/>
</el-form-item>
<el-form-item label="进货单ID" prop="purchaseId" required>
<el-select
v-model="form.purchaseId"
filterable
clearable
remote
reserve-keyword
placeholder="请选择进货单"
:remote-method="fetchPurchaseOptions"
:loading="purchaseLoading"
style="width: 100%"
default-first-option
>
<el-option
v-for="item in purchaseOptions"
:key="item.purchase_id"
:label="`#${item.purchase_id} ${parseTime(item.purchase_time,'{y}-{m}-{d}')}`"
:value="item.purchase_id"
/>
</el-select>
</el-form-item>
<el-form-item label="库存数量">
<el-input
v-model="stockDisplay"
disabled
placeholder="自动获取库存数量"
/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import {
listWarning,
getWarning,
delWarning,
addWarning,
updateWarning,
} from "@/api/pill/warning"
import { listDrugs } from "@/api/pill/drug"
import { listFactories } from "@/api/pill/factory"
import { listPurchases } from "@/api/pill/purchase"
export default {
name: "Warning",
data() {
return {
loading: false,
ids: [],
single: true,
multiple: true,
showSearch: true,
total: 0,
warningList: [],
title: "",
open: false,
drugOptions: [],
factoryOptions: [],
purchaseOptions: [],
drugLoading: false,
factoryLoading: false,
purchaseLoading: false,
queryParams: {
pageNum: 1,
pageSize: 10,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
},
form: {
warningId: null,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
},
stockDisplay: "",
rules: {
drugId: [{ required: true, message: "药品ID不能为空", trigger: "change" }],
factoryId: [{ required: true, message: "厂家ID不能为空", trigger: "change" }],
productionDate: [
{ required: true, message: "药品生产日期不能为空", trigger: "change" },
],
validityPeriod: [
{ required: true, message: "保质期不能为空", trigger: "blur" },
{ type: "number", min: 0, message: "保质期必须大于等于0", trigger: "blur" },
],
purchaseId: [{ required: true, message: "进货单ID不能为空", trigger: "change" }],
},
}
},
watch: {
"form.drugId"(newVal) {
this.updateStockDisplay()
},
},
created() {
this.getList()
},
methods: {
/** 解析时间 */
parseTime(time, pattern) {
if (!time) return "-"
const date = new Date(time)
const Y = date.getFullYear()
const M = (date.getMonth() + 1).toString().padStart(2, "0")
const D = date.getDate().toString().padStart(2, "0")
const h = date.getHours().toString().padStart(2, "0")
const m = date.getMinutes().toString().padStart(2, "0")
const s = date.getSeconds().toString().padStart(2, "0")
if (!pattern) return `${Y}-${M}-${D} ${h}:${m}:${s}`
return pattern
.replace("{y}", Y)
.replace("{m}", M)
.replace("{d}", D)
.replace("{h}", h)
.replace("{i}", m)
.replace("{s}", s)
},
/** 计算剩余天数 */
getRemainingDays(productionDate, validityPeriod) {
if (!productionDate || validityPeriod == null) return ""
const prodDate = new Date(productionDate)
const expireDate = new Date(
prodDate.getTime() + validityPeriod * 24 * 60 * 60 * 1000
)
const now = new Date()
const diffTime = expireDate.getTime() - now.getTime()
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
return diffDays >= 0 ? `${diffDays}天` : `已过期${-diffDays}天`
},
/** 查询列表 */
getList() {
this.loading = true
listWarning(this.queryParams)
.then((response) => {
this.warningList = response.rows
this.total = response.total
this.loading = false
})
.catch(() => {
this.loading = false
})
},
// 取消按钮
cancel() {
this.open = false
this.reset()
},
// 表单重置
reset() {
this.form = {
warningId: null,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
}
this.stockDisplay = ""
this.resetForm("form")
},
// 重置el-form
resetForm(refName) {
if (this.$refs[refName]) {
this.$refs[refName].resetFields()
}
},
/** 搜索按钮 */
handleQuery() {
this.queryParams.pageNum = 1
this.getList()
},
/** 重置搜索 */
resetQuery() {
this.resetForm("queryForm")
this.queryParams = {
pageNum: 1,
pageSize: 10,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
}
this.handleQuery()
},
// 表格选中
handleSelectionChange(selection) {
this.ids = selection.map((item) => item.warningId)
this.single = selection.length !== 1
this.multiple = !selection.length
},
/** 新增 */
handleAdd() {
this.reset()
this.open = true
this.title = "添加药品有效期预警,用于监控药品保质期"
// 预加载下拉选项,方便选择
this.fetchDrugOptions()
this.fetchFactoryOptions()
this.fetchPurchaseOptions()
},
/** 修改 */
async handleUpdate(row) {
this.reset()
const warningId = row?.warningId || this.ids[0]
const response = await getWarning(warningId)
this.form = response.data
this.open = true
this.title = "修改药品有效期预警,用于监控药品保质期"
// 确保修改时对应选项存在于下拉列表中,否则下拉无法显示label
await this.fetchDrugOptions()
if (!this.drugOptions.find(d => d.drug_id === this.form.drugId)) {
try {
const res = await listDrugs({ drugId: this.form.drugId, pageNum: 1, pageSize: 1 })
if (res.rows.length) this.drugOptions.push(res.rows[0])
} catch {}
}
await this.fetchFactoryOptions()
if (!this.factoryOptions.find(f => f.factory_id === this.form.factoryId)) {
try {
// 如果你有查询单个厂家的接口,可调用补充。示例:
// const res = await getFactoryById(this.form.factoryId)
// this.factoryOptions.push(res.data)
} catch {}
}
await this.fetchPurchaseOptions()
if (!this.purchaseOptions.find(p => p.purchase_id === this.form.purchaseId)) {
try {
// 同理,查询单个进货单接口,示例:
// const res = await getPurchaseById(this.form.purchaseId)
// this.purchaseOptions.push(res.data)
} catch {}
}
// 更新库存显示
this.updateStockDisplay()
},
/** 提交表单 */
submitForm() {
this.$refs["form"].validate((valid) => {
if (valid) {
if (this.form.warningId != null) {
updateWarning(this.form).then(() => {
this.$modal.msgSuccess("修改成功")
this.open = false
this.getList()
})
} else {
addWarning(this.form).then(() => {
this.$modal.msgSuccess("新增成功")
this.open = false
this.getList()
})
}
}
})
},
/** 删除 */
handleDelete(row) {
const warningIds = row?.warningId || this.ids
this.$modal
.confirm(
`是否确认删除药品有效期预警,用于监控药品保质期编号为"${warningIds}"的数据项?`
)
.then(() => delWarning(warningIds))
.then(() => {
this.getList()
this.$modal.msgSuccess("删除成功")
})
.catch(() => {})
},
/** 导出 */
handleExport() {
this.download(
"pill/warning/export",
{
...this.queryParams,
},
`warning_${new Date().getTime()}.xlsx`
)
},
// 远程搜索下拉框 - 药品
async fetchDrugOptions(query = '') {
this.drugLoading = true
try {
const res = await listDrugs({ drugName: query, pageNum: 1, pageSize: 20 })
this.drugOptions = res.rows || []
} catch (error) {
this.drugOptions = []
}
this.drugLoading = false
},
// 远程搜索下拉框 - 厂家
async fetchFactoryOptions(query = '') {
this.factoryLoading = true
try {
const res = await listFactories({ factoryName: query, pageNum: 1, pageSize: 20 })
this.factoryOptions = res.rows || []
} catch (error) {
this.factoryOptions = []
}
this.factoryLoading = false
},
// 远程搜索下拉框 - 进货单
async fetchPurchaseOptions(query = '') {
this.purchaseLoading = true
try {
const res = await listPurchases({ purchaseId: query, pageNum: 1, pageSize: 20 })
this.purchaseOptions = res.rows || []
} catch (error) {
this.purchaseOptions = []
}
this.purchaseLoading = false
},
// 根据选中的药品ID,更新库存显示
updateStockDisplay() {
if (!this.form.drugId) {
this.stockDisplay = ""
return
}
const drug = this.drugOptions.find((d) => d.drug_id === this.form.drugId)
if (drug && drug.num !== undefined) {
this.stockDisplay = drug.num
} else {
listDrugs({ drugId: this.form.drugId, pageNum: 1, pageSize: 1 })
.then(res => {
if (res.rows && res.rows.length > 0) {
this.stockDisplay = res.rows[0].num || ""
} else {
this.stockDisplay = ""
}
})
.catch(() => (this.stockDisplay = ""))
}
},
},
}
</script>
fetchXXXOptions支持空字符串参数,避免空查询时不请求;default-first-option辅助默认选择(可以根据UI需要去掉);这样改完,一般就可以解决新增弹窗下拉框没数据,无法选择的问题。后端接口也要支持空查询参数返回数据。
需要我帮你写后端单条查询接口示例或者其他细节,也可以告诉我~
remote远程搜索功能(即不边输入边搜索)el-select显示data里定义类似 drugList、factoryList的数组created或者弹窗打开handleAdd时,从后端接口拉取对应完整数据列表到这两个变量<el-select>的v-model上,使用drugList、factoryList作为选项<template>
<el-form-item label="药品名称" prop="drugId">
<el-select v-model="form.drugId" placeholder="请选择药品" clearable>
<el-option
v-for="item in drugList"
:key="item.drugId"
:label="item.drugName"
:value="item.drugId"
/>
</el-select>
</el-form-item>
<el-form-item label="生产厂家" prop="factoryId">
<el-select v-model="form.factoryId" placeholder="请选择生产厂家" clearable>
<el-option
v-for="item in factoryList"
:key="item.factoryId"
:label="item.factoryName"
:value="item.factoryId"
/>
</el-select>
</el-form-item>
</template>
<script>
import { listDrugs } from '@/api/pill/drug'
import { listFactories } from '@/api/pill/factory'
export default {
data() {
return {
form: {
drugId: null,
factoryId: null,
},
drugList: [],
factoryList: [],
}
},
created() {
this.loadDrugList()
this.loadFactoryList()
},
methods: {
async loadDrugList() {
try {
// 这里我们不传过滤条件,后台会返回默认的全部或者前X条数据
const res = await listDrugs({ pageNum: 1, pageSize: 1000 })
this.drugList = res.rows.map(item => ({
drugId: item.drug_id,
drugName: item.drug_name,
}))
} catch (error) {
this.drugList = []
}
},
async loadFactoryList() {
try {
const res = await listFactories({ pageNum: 1, pageSize: 1000 })
this.factoryList = res.rows.map(item => ({
factoryId: item.factory_id,
factoryName: item.factory_name,
}))
} catch (error) {
this.factoryList = []
}
},
},
}
</script>
remote、filterable、远程搜索相关属性,转回本地选项;drugList、factoryList;drugId 和 drugName 与后端字段对应,你可以对返回数据做适当转换;purchaseList)。filterable,但不使用远程搜索,ElSelect本身支持本地过滤。如果你需要,我也可以帮你帮忙写完整弹窗代码和加载流程示范。
下面是基于你需求的完整示例Vue组件代码,演示了如何在页面加载时获取完整药品列表和厂家列表,绑定到本地el-select,不使用远程搜索,方便直接选择:
<template>
<el-dialog
:visible.sync="open"
title="新增/编辑药品有效期预警"
width="500px"
append-to-body
@close="cancel"
>
<el-form ref="form" :model="form" :rules="rules" label-width="120px">
<el-form-item label="药品名称" prop="drugId" required>
<el-select v-model="form.drugId" placeholder="请选择药品" clearable filterable>
<el-option
v-for="item in drugList"
:key="item.drugId"
:label="item.drugName"
:value="item.drugId"
/>
</el-select>
</el-form-item>
<el-form-item label="生产厂家" prop="factoryId" required>
<el-select v-model="form.factoryId" placeholder="请选择生产厂家" clearable filterable>
<el-option
v-for="item in factoryList"
:key="item.factoryId"
:label="item.factoryName"
:value="item.factoryId"
/>
</el-select>
</el-form-item>
<el-form-item label="药品生产日期" prop="productionDate" required>
<el-date-picker
v-model="form.productionDate"
type="date"
placeholder="请选择生产日期"
value-format="yyyy-MM-dd"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="保质期(天)" prop="validityPeriod" required>
<el-input
v-model.number="form.validityPeriod"
type="number"
min="0"
placeholder="请输入保质期"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="进货单ID" prop="purchaseId" required>
<el-select v-model="form.purchaseId" placeholder="请选择进货单" clearable filterable>
<el-option
v-for="item in purchaseList"
:key="item.purchaseId"
:label="`#${item.purchaseId} ${formatDate(item.purchaseTime)}`"
:value="item.purchaseId"
/>
</el-select>
</el-form-item>
<el-form-item label="库存数量">
<el-input v-model="stockDisplay" disabled placeholder="自动获取库存数量" />
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="submitForm">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
import { listDrugs } from '@/api/pill/drug'
import { listFactories } from '@/api/pill/factory'
import { listPurchases } from '@/api/pill/purchase'
export default {
data() {
return {
open: false,
form: {
warningId: null,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
},
drugList: [],
factoryList: [],
purchaseList: [],
stockDisplay: '',
rules: {
drugId: [{ required: true, message: '请选择药品', trigger: 'change' }],
factoryId: [{ required: true, message: '请选择厂家', trigger: 'change' }],
productionDate: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
validityPeriod: [
{ required: true, message: '请输入保质期', trigger: 'blur' },
{ type: 'number', min: 0, message: '保质期不能小于0', trigger: 'blur' },
],
purchaseId: [{ required: true, message: '请选择进货单', trigger: 'change' }],
},
}
},
methods: {
openDialog(editData) {
this.open = true
if (editData) {
this.form = Object.assign({}, editData)
if (this.form.productionDate) {
// 确保productionDate为Date对象
this.form.productionDate = new Date(this.form.productionDate)
}
this.updateStockDisplay()
} else {
this.form = {
warningId: null,
drugId: null,
factoryId: null,
productionDate: null,
validityPeriod: null,
purchaseId: null,
}
this.stockDisplay = ''
}
// 弹窗打开时加载下拉数据(如果为空)
if (!this.drugList.length) this.loadDrugList()
if (!this.factoryList.length) this.loadFactoryList()
if (!this.purchaseList.length) this.loadPurchaseList()
},
cancel() {
this.open = false
this.$refs.form && this.$refs.form.resetFields()
},
async submitForm() {
this.$refs.form.validate(valid => {
if (valid) {
// 这里提交保存逻辑
this.$message.success('表单验证通过,提交保存即可')
this.open = false
} else {
return false
}
})
},
async loadDrugList() {
try {
const res = await listDrugs({ pageNum: 1, pageSize: 1000 })
this.drugList = res.rows.map(item => ({
drugId: item.drug_id,
drugName: item.drug_name,
stock: item.num, // 如果有库存字段
}))
} catch {
this.drugList = []
}
},
async loadFactoryList() {
try {
const res = await listFactories({ pageNum: 1, pageSize: 1000 })
this.factoryList = res.rows.map(item => ({
factoryId: item.factory_id,
factoryName: item.factory_name,
}))
} catch {
this.factoryList = []
}
},
async loadPurchaseList() {
try {
const res = await listPurchases({ pageNum: 1, pageSize: 1000 })
this.purchaseList = res.rows.map(item => ({
purchaseId: item.purchase_id,
purchaseTime: item.purchase_time,
}))
} catch {
this.purchaseList = []
}
},
updateStockDisplay() {
const drug = this.drugList.find(d => d.drugId === this.form.drugId)
this.stockDisplay = drug ? drug.stock || '' : ''
},
formatDate(date) {
if (!date) return ''
const d = new Date(date)
const y = d.getFullYear()
const m = (d.getMonth() + 1).toString().padStart(2, '0')
const day = d.getDate().toString().padStart(2, '0')
return `${y}-${m}-${day}`
},
},
watch: {
'form.drugId'(newVal) {
this.updateStockDisplay()
},
},
mounted() {
// 页面加载预加载下拉数据,也可根据需求放到弹窗打开时加载
this.loadDrugList()
this.loadFactoryList()
this.loadPurchaseList()
},
}
</script>
drugList、factoryList、purchaseListfilterable但取消远程搜索相关配置formatDate,用于进货单显示openDialog()打开弹窗,传入编辑的数据对象,或者不传,执行“新增”如果你的页面中不仅有弹窗,还需要列表页面,建议列表页面也调接口加载,然后传递数据给弹窗,避免重复多次请求。
如有问题或需帮忙写完整列表+弹窗示例,欢迎继续提问!
Not yet included in a published release.
<resultMap id="PillExpiryWarningResult" type="com.ruoyi.pill.domain.PillExpiryWarning">
<result property="warningId" column="warning_id" />
<result property="drugId" column="drug_id" />
<result property="factoryId" column="factory_id" />
<result property="productionDate" column="production_date" />
<result property="validityPeriod" column="validity_period" />
<result property="purchaseId" column="purchase_id" />
<result property="stock" column="stock" />
<result property="createTime" column="create_time" />
<result property="drugName" column="drug_name"/>
<result property="factoryName" column="factory_name"/>
<result property="purchaseTime" column="purchase_time"/>
<result property="daysToExpire" column="days_to_expire"/>
</resultMap>
<sql id="BaseSelectSql">
select
pe.warning_id,
pe.drug_id,
pe.factory_id,
pe.production_date,
pe.validity_period,
pe.purchase_id,
pd.num as stock,
pe.create_time,
pd.drug_name,
pf.factory_name,
pp.purchase_time,
datediff(date_add(pe.production_date, interval pe.validity_period day), curdate()) as days_to_expire
from pill_expiry_warning pe
LEFT JOIN pill_drug pd ON pe.drug_id = pd.drug_id
LEFT JOIN pill_factory pf ON pe.factory_id = pf.factory_id
LEFT JOIN pill_purchase pp ON pe.purchase_id = pp.purchase_id
</sql>
<select id="selectPillExpiryWarningList" parameterType="com.ruoyi.pill.domain.PillExpiryWarning" resultMap="PillExpiryWarningResult">
<include refid="BaseSelectSql"/>
<where>
<if test="drugId != null "> and pe.drug_id = #{drugId}</if>
<if test="factoryId != null "> and pe.factory_id = #{factoryId}</if>
<if test="productionDate != null "> and pe.production_date = #{productionDate}</if>
<if test="validityPeriod != null "> and pe.validity_period = #{validityPeriod}</if>
<if test="purchaseId != null "> and pe.purchase_id = #{purchaseId}</if>
</where>
</select>
<select id="selectPillExpiryWarningByWarningId" parameterType="Long" resultMap="PillExpiryWarningResult">
<include refid="BaseSelectSql"/>
where pe.warning_id = #{warningId}
</select>
<insert id="insertPillExpiryWarning" parameterType="com.ruoyi.pill.domain.PillExpiryWarning" useGeneratedKeys="true" keyProperty="warningId">
insert into pill_expiry_warning
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="drugId != null">drug_id,</if>
<if test="factoryId != null">factory_id,</if>
<if test="productionDate != null">production_date,</if>
<if test="validityPeriod != null">validity_period,</if>
<if test="purchaseId != null">purchase_id,</if>
<if test="stock != null">stock,</if>
<if test="createTime != null">create_time,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="drugId != null">#{drugId},</if>
<if test="factoryId != null">#{factoryId},</if>
<if test="productionDate != null">#{productionDate},</if>
<if test="validityPeriod != null">#{validityPeriod},</if>
<if test="purchaseId != null">#{purchaseId},</if>
<if test="stock != null">#{stock},</if>
<if test="createTime != null">#{createTime},</if>
</trim>
</insert>
<update id="updatePillExpiryWarning" parameterType="com.ruoyi.pill.domain.PillExpiryWarning">
update pill_expiry_warning
<set>
<if test="drugId != null">drug_id = #{drugId},</if>
<if test="factoryId != null">factory_id = #{factoryId},</if>
<if test="productionDate != null">production_date = #{productionDate},</if>
<if test="validityPeriod != null">validity_period = #{validityPeriod},</if>
<if test="purchaseId != null">purchase_id = #{purchaseId},</if>
<if test="stock != null">stock = #{stock},</if>
<if test="createTime != null">create_time = #{createTime},</if>
</set>
where warning_id = #{warningId}
</update>
<delete id="deletePillExpiryWarningByWarningId" parameterType="Long">
delete from pill_expiry_warning where warning_id = #{warningId}
</delete>
<delete id="deletePillExpiryWarningByWarningIds" parameterType="Long[]">
delete from pill_expiry_warning where warning_id in
<foreach item="warningId" collection="array" open="(" separator="," close=")">
#{warningId}
</foreach>
</delete>
public void setPurchaseTime(Date purchaseTime) { this.purchaseTime = purchaseTime; }
public Long getDaysToExpire() { return daysToExpire; }
public void setDaysToExpire(Long daysToExpire) { this.daysToExpire = daysToExpire; }
@Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("warningId", getWarningId()) .append("drugId", getDrugId()) .append("factoryId", getFactoryId()) .append("productionDate", getProductionDate()) .append("validityPeriod", getValidityPeriod()) .append("purchaseId", getPurchaseId()) .append("stock", getStock()) .append("drugName", getDrugName()) .append("factoryName", getFactoryName()) .append("purchaseTime", getPurchaseTime()) .append("daysToExpire", getDaysToExpire()) .append("createTime", getCreateTime()) .toString(); } } package com.ruoyi.pill.mapper;