关于element-ui中el-autocomplete使用:fetch-suggestions内容不显示的问题

问题描述和解决

我希望使用element-ui中的el-autocomplete 标签完成一个带输入建议的输入框,内容通过axios从后端获取,官网的demo是这样的

于是照着这个demo敲了一个方法

queryType(queryString, cb){
     this.$axios({
         method: "post",
         url: "/goodstype",
     }).then(res=>{
         if(res.data.code == 200){
             cb(res.data.data);
         }
     })
 }

表单代码

<el-form-item label="类型" prop="goodstype">
    <el-autocomplete :fetch-suggestions="queryType" v-model="goods.goodstype" style="width: 80%;"></el-autocomplete>
</el-form-item>

但是运行只会出现一个不全的白色框框,数据也不显示,于是上网查询了一下,找到了这位大佬的博客:element-ui带输入建议的input框踩坑(输入建议空白以及会闪出上一次的输入建议问题)
原来是因为输入建议的数据必须为对象数组(data=[{}, {}, {}…]),且对象必须包含“value”: “xxx”键值对,比如:{“value”: item.username},当然也可以添加其他内容:{“value”: item.username, “id”: item.id}

queryType(queryString, cb){
    this.$axios({
        method: "post",
        url: "/goodstype",
        data: {},
    }).then(res=>{
        if(res.data.code == 200){
            for(let item of res.data.data){
                this.types.push({"value": item.name})
            }
            cb(this.types);
        }
    })
}

types是自己定义在data中用来接收后端数据的数组


新的问题

但是这样还有一个问题,如果你重复点击输入框,之前的输入建议内容还会一直保存在types中,所以点击几次之后,你会看到很多重复的选项。因此在获取内容之前还要对types进行清空,修改后如下

queryType(queryString, cb){
   this.$axios({
       method: "post",
       url: "/goodstype",
       data: {},
   }).then(res=>{
       if(res.data.code == 200){
           if(this.types.length!=0){
               this.types = [];
           }
           for(let item of res.data.data){
               this.types.push({"value": item.name})
           }
           cb(this.types);
       }
   })
}

此外,如果加载输入建议时会闪烁,可以给el-autocomplete 加上:debounce=“0”属性


以下是完成后的截图

以上是我碰到的一个小问题,如有不对的地方,欢迎评论区多多讨论呀!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值