如何从异步方法访问 Vue 中的数据字段?

How to access data fields in Vue from async method?

代码:

export default {
   data() {
        return {
            nameCity: '',
        }
    },
    methods: {
        findCity(event){
            event.preventDefault()
            findCityCust().then(function(response) { 
                console.log(response)
               this.nameCity = response;
            })
        }, 
    },
}

这里 - this.nameCity = 响应; - 抛出一个错误 Uncaught (in promise) TypeError: Cannot read properties of undefined

如何在 Vue 3 中使用异步方法中的字段?

标准函数没有绑定到组件,试试箭头函数:

export default {
   data() {
        return {
            nameCity: '',
        }
    },
    methods: {
        findCity(event){
            event.preventDefault()
            findCityCust().then((response) => { 
                console.log(response)
               this.nameCity = response;
            })
        }, 
    },
}

错误是由this

引起的

differences-between-arrow-and-regular-functions: this value

function(){}中,this是全局对象

() => {}中,this是当前的Vue实例

所以改成

findCityCust().then(response => { 
    console.log(response)
    this.nameCity = response;
})

methods: {
    async findCity(event){
        event.preventDefault()
        this.nameCity = await findCityCust();
    }, 
},