Vue组件computed内address变量未定义报错求助
解决Vue组件中computed属性的this指向问题及自动补全提示文本优化
嘿,我一眼就揪出问题所在啦!你在dummyText这个computed属性里用了箭头函数,这直接导致this没指向Vue组件实例,所以this.address是undefined,自然会抛出“Cannot read property 'length' of undefined”的错误。
为啥其他地方的address能正常用?
因为你在methods里的getAsyncData用的是普通函数,Vue会自动给组件内的普通方法绑定组件实例的this,所以能正常访问address;但箭头函数不会创建自己的this,它会继承外层作用域的this,这里外层是模块作用域而非组件实例,自然拿不到组件里的address。
修复步骤
- 把computed属性的箭头函数改成普通函数,让
this正确指向组件实例 - 优化
nothingFound的状态管理:当前代码只在返回空结果时设为true,但用户后续输入有匹配结果时,需要把它重置为false,不然提示文本会一直停留在“没有找到”
修改后的完整代码如下:
<template lang="pug"> b-field(label="Your address?") b-autocomplete( rounded, v-model="address", :data="data", placeholder="Start typing", icon="magnify", @input="getAsyncData", @select="option => selected = option", :loading="isFetching" ) template(slot="empty") {{ dummyText }} </template> <script> import axios from 'axios' import debounce from 'lodash/debounce' export default { data() { return { data: [], address: '', selected: null, isFetching: false, nothingFound: false, test: false } }, computed: { // 这里改成普通函数! dummyText() { if (this.address.length > 0 && this.nothingFound) { return 'There is no such address' } else { return 'Keep typing' } } }, methods: { getAsyncData: debounce(function () { this.isFetching = true // 新增:请求开始时重置状态,避免旧提示残留 this.nothingFound = false axios.post('https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address', { "query": this.address, "count": 8 }, { headers: { 'Authorization': 'Token sometoken', 'Content-Type': 'application/json', 'Accept': 'application/json', } }) .then(response => { this.isFetching = false this.data = Object.values(response.data.suggestions) // 同步更新nothingFound状态,不管有没有结果都覆盖 this.nothingFound = response.data.suggestions.length === 0 console.log(this.address.length) // 现在这里正常,computed里也正常了 }) .catch(error => { this.isFetching = false // 错误时重置状态,避免加载状态卡死 this.nothingFound = false console.log(error); }) }, 300) } } </script>
额外小提示
Buefy的b-autocomplete的empty插槽只会在data为空时显示,你的逻辑刚好匹配这个场景,优化后就能完美区分“未输入”和“无匹配”两种提示啦。
内容的提问来源于stack exchange,提问作者Elijah Ellanski
相关产品推荐
相关产品推荐

