ganhuo

导航

 

需求描述

没有什么技术难度,需求如下,要求上来默认加载几个选项,然后根据用户的输入,实时更新选项,且支持用户新增。(请看gif)

image

解决方案

首先要找到了el-select组件,然后里面有一个远程搜索功能。
官方文档:https://element-plus.org/zh-CN/component/select.html

image

代码如下:

<el-select
  v-model="otherForm.other"
  filterable
  allow-create
  remote
  reserve-keyword
  placeholder="请输入自定义时区"
  :remote-method="getZoneAddress"
  :loading="otherForm.loading"
  remote-show-suffix
  style="width: 100%"
>
  <el-option
    v-for="(item, index) in otherForm.options"
    :key="index"
    :label="item"
    :value="item"
  />
</el-select>

代码中remote-show-suffix属性,用于展示下拉的那个图标,allow-create属性,用于新增,remote-method属性,绑定远程搜索的函数

const otherForm = reactive({
  other: '',
  loading: false,
  options: []
})

const getZoneAddress = (val) => {
  otherForm.loading = true
  zoneAddress({ other: val })
    .then((resp) => {
      otherForm.options = resp.data
    })
    .catch((error) => {
      console.log(error)
    })
    .finally(() => {
      otherForm.loading = false
    })
}

代码中zoneAddress是通过axios访问后台数据,并且给结果存储到otherForm.options中,函数getZoneAddress的参数val,是用户输入的值。

关于otherForm.options的格式['a','b','c']字符串数组就行

以上就简单实现了,基于vue3+elementplus+ts,希望会对你有所帮助。

image

posted on 2024-03-05 16:22  战力助手  阅读(1313)  评论(0)    收藏  举报