select-带远程搜索
2025年5月7日大约 2 分钟
select-带远程搜索
说明:
在实际工作中,面对复杂的业务逻辑,有时需要带远程搜索的选择框?具体来说就是用户选择选项的时候,一个接口提供一些常用的默认选项.
但是如果默认选项里面没有这些选项,就需要提供搜索功能,通过搜索查找出选项,这样用户就可以完成这个选择动作
实际解决办法:
类似于这样的情况,往往不只一处地方使用,通常需要单独封装成一个对应在业务逻辑下的组件.这样做也是为了后续维护方便
示例:
该示例是以商品品牌为例,用户选择商品品牌
路径
src\pages\component\youhu-shop\v1\select\goods\selectGoodsBrand.vue
代码
<template>
<div>
<el-select
v-model="selectId"
clearable
filterable
remote
placeholder="请选择或输入关键词"
:remote-method="searchGoodsBrand"
:loading="goodsBrandLoading"
>
<el-option
v-for="item in goodsBrandOptions"
:key="item.id"
:label="item.brand_name"
:value="item.id"
/>
</el-select>
</div>
</template>
<script>
import { defaultGoodsBrand, findGoodsBrand } from '@/api/youhu-shop/V1/goods/goodsBrand'
export default
{
// 组件名称
name: 'SelectGoodsBrand',
// 组件
components:
{
},
props:
{
// 品牌id
goodsBrandId: {
type: [Number, String],
default: null
},
beforeGoodsBrand: {
type: Object,
default: () =>
{
return {}
}
}
},
// 数据
data()
{
return {
// 选择的id容器
selectId: this.goodsBrandId,
// 选品牌择容器
goodsBrandSelect: [],
// 品牌加载控制
goodsBrandLoading: false
}
},
// 计算属性
computed:
{
goodsBrandOptions:
{
set(value)
{
this.goodsBrandSelect = value
},
get()
{
return this.goodsBrandSelect
}
}
},
// 监听
watch:
{
selectId(value)
{
// console.log(value)
this.$emit('update:goodsBrandId', value)
}
},
// 实例创建之前
beforeCreate()
{
},
// 创建
created()
{
},
// 挂载之前
beforeMount()
{
},
// 挂载 --常用
mounted()
{
this.defaultOptions()
// 这里是修改的时候,传入的默认值
if (Object.getOwnPropertyNames(this.beforeGoodsBrand).length > 1)
{
this.goodsBrandOptions = [{ id: this.beforeGoodsBrand.id, brand_name: this.beforeGoodsBrand.brand_name }]
}
},
// 更新之前
beforeUpdate()
{
},
// 跟新后
updated()
{
},
// 销毁之前
beforeDestroy()
{
},
// 销毁后
destroyed()
{
},
// 方法
methods:
{
// 获取默认选项
async defaultOptions()
{
// limit 是默认选项的查询数量
const goodsBrandList = await defaultGoodsBrand({ limit: 10 }).then(res =>
{
return new Promise((resolve, reject) =>
{
if (res && res.code === 0)
{
resolve(res.data)
}
else
{
reject('获取品牌选项失败')
}
})
})
this.goodsBrandSelect = goodsBrandList
},
// 查找地址选项 find 是查找的关键词
async findOptions(find)
{
const goodsBrandList = await findGoodsBrand({ find: find, barnd_type: null }).then(res =>
{
return new Promise((resolve, reject) =>
{
if (res && res.code === 0)
{
resolve(res.data)
}
else
{
reject('获取品牌选项失败')
}
})
})
if (goodsBrandList && goodsBrandList.length > 0)
{
this.goodsBrandOptions = goodsBrandList
this.goodsBrandLoading = false
}
},
// 搜品牌
searchGoodsBrand(query)
{
if (query !== '')
{
this.goodsBrandLoading = true
this.findOptions(query)
}
else
{
this.goodsBrandLoading = false
this.defaultOptions()
}
}
}
}
</script>
<style lang='scss' scoped>
</style>