iView Select选择器怎么实现远程搜索并保持已选项不被清空?

Mr.淑涵 阅读 230

我在用 iView 的 Select 做一个带远程搜索的下拉框,用户选了几个选项后,再输入关键词搜索,结果之前选中的项全没了。明明文档里说 multiple 模式下应该保留已选项啊?

我试过在 on-query-change 里手动把 model 重新赋值回去,但界面还是清空了。是不是我哪里配置错了?相关代码大概是这样的:

<Select
  v-model="selectedUsers"
  filterable
  multiple
  remote
  :remote-method="searchUsers"
  :loading="loading"
>
  <Option v-for="item in userOptions" :value="item.id" :key="item.id">
    {{ item.name }}
  </Option>
</Select>
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
 ___诗雅
问题在于远程搜索后 userOptions 里没有已选中的项,组件渲染时找不到对应 value 就清空了。

在搜索方法里把已选中的项合并进去:

searchUsers(query) {
if (!query) {
this.userOptions = []
return
}
// 你的远程搜索请求
this.loading = true
this.$http.get('/api/users?q=' + query).then(res => {
// 关键:把已选中的项也加进去,防止被清空
const selectedIds = this.selectedUsers
const selectedItems = this.userOptions.filter(item => selectedIds.includes(item.id))
this.userOptions = [...selectedItems, ...res.data]
this.loading = false
})
}


或者更简单的做法——把 selectedUsers 对应的完整对象存下来,搜索时直接拼进去。
点赞
2026-03-11 11:03