VueJS:仅在计算内部未定义变量

vue.js Vue.js

Pro小卤蛋A

2020-03-20

我正在尝试使用Vue,Nuxt,Axios和Buefy进行异步自动完成输入。它基本上可以正常工作,但是当用户刚开始输入并且什么都没有显示时,以及对于该请求没有找到任何内容时,我需要使用不同的字符串。

我正在检查计算变量,如果输入值不为空,并且axios返回空数组以处理找不到请求地址的情况。但这会导致错误

无法读取未定义的属性“长度”

奇怪的是,address变量已在组件的其他部分成功使用。

我的Vue文件如下:

<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) { // This will return error
                return 'There is no such address'
            } else {
                return 'Keep typing'
            }
        }
    },

    methods: {
        getAsyncData: debounce(function () {
            this.isFetching = true

            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)
                    if (response.data.suggestions.length===0) this.nothingFound = true
                    console.log(this.address.length) // This will work
                })
                .catch(error => {
                    this.isFetching = false
                    console.log(error);
                })
        }, 300)
    }
}
</script>

这不是关于ssr的问题,我试图初始化已安装挂钩中的组件。认为我遗漏了一些明显的东西,但是我已经花了几个小时试图解决这个问题,但没有成功

第2465篇《VueJS:仅在计算内部未定义变量》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android