Buefy Autocomplete对接API求助:输入内容无法被API接收
问题:Buefy Autocomplete 无法将输入文本传给API
我们尝试把Buefy Autocomplete组件和API对接,但API要求传入对象。不管怎么试,输入框里的文本都传不到API,只有硬编码传入时才有效,这显然不实用。我们是学徒,试过各种方法都没用,不知道怎么改代码才能获取API返回的建议,求帮助。
现有代码
模板部分
<b-field> <b-autocomplete v-model="text" :data="data" placeholder="e.g. Java" field="title" :loading="isFetching" @typing="newPost()" @select="(selected) => addSkill(selected)" > </b-autocomplete> </b-field>
脚本部分
/* import debounce from "lodash/debounce"; */ import axios from "axios"; export default { data() { return { data: [], skills: [], selected: "", isFetching: false, text: "", }; }, methods: { newPost(data) { const session_url = "Link to API"; const config = { auth: { username: , password: , }, headers: { Accept: "application/json", "Content-Type": "application/json", }, }; data = { text: "" }; axios .post(session_url, data, config) .then(function (response) { console.log("Authenticated"); console.log(data); response.data = []; response.data.forEach((data) => this.data.push(data)); }) .catch(function () { console.log("Error on Authentication"); }); }, addSkill(data) { if (data != null) this.skills.push(data.title); return; }, deleteSkill: function (skill) { this.skills.splice(skill, 1); }, }, };
问题分析与修正
你的代码存在几个关键错误,导致输入文本无法传递给API,同时也无法正确接收返回的建议:
- 未传递输入文本到API:
@typing="newPost()"调用方法时未传参,且在newPost里硬编码了data = { text: "" },直接覆盖了输入内容。 - 清空了API返回数据:
response.data = [];这行代码直接清空了API返回的结果,导致无法获取建议列表。 this指向错误:普通function回调里的this不指向Vue实例,this.data.push(data)会报错。- 未控制加载状态:请求前后没有切换
isFetching值,导致加载动画不生效。
修正后的代码
模板部分
<b-field> <b-autocomplete v-model="text" :data="data" placeholder="e.g. Java" field="title" :loading="isFetching" <!-- 直接传递输入文本给newPost方法 --> @typing="newPost" @select="(selected) => addSkill(selected)" > </b-autocomplete> </b-field>
脚本部分
/* import debounce from "lodash/debounce"; */ import axios from "axios"; export default { data() { return { data: [], skills: [], selected: "", isFetching: false, text: "", }; }, methods: { // 接收输入框的文本作为参数 async newPost(inputText) { // 输入为空时直接清空建议列表 if (!inputText.trim()) { this.data = []; return; } const session_url = "Link to API"; const config = { auth: { // 填写你的认证信息 username: "your-username", password: "your-password", }, headers: { Accept: "application/json", "Content-Type": "application/json", }, }; try { this.isFetching = true; // 用输入文本构造API需要的请求对象 const requestData = { text: inputText }; const response = await axios.post(session_url, requestData, config); // 更新建议列表为API返回的数据 this.data = [...response.data]; } catch (error) { console.error("请求API失败:", error); this.data = []; } finally { this.isFetching = false; } }, addSkill(data) { if (data) this.skills.push(data.title); }, deleteSkill(skillIndex) { this.skills.splice(skillIndex, 1); }, }, };
额外优化建议
- 建议给
@typing事件添加防抖(取消注释import debounce后,将newPost改为防抖函数),避免频繁请求API:newPost: debounce(async function(inputText) { // 原有逻辑 }, 300), - 确认API的请求方式是否为
POST,如果是GET,需改为axios.get并通过params传递参数。
内容的提问来源于stack exchange,提问作者Hedororo
相关产品推荐
相关产品推荐

