问题描述和解决
我希望使用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”属性
以下是完成后的截图
以上是我碰到的一个小问题,如有不对的地方,欢迎评论区多多讨论呀!