3

Code:

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

And here - this.nameCity = response; - throws an error Uncaught (in promise) TypeError: Cannot read properties of undefined

How to work with fields from asynchronous methods in Vue 3?

yuort89
  • 35
  • 3

2 Answers2

2

the error is caused by this

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

in function(){}, this is the global object

in () => {}, this is the current Vue instance

so change it to

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

or

methods: {
    async findCity(event){
        event.preventDefault()
        this.nameCity = await findCityCust();
    }, 
},
DengSihan
  • 2,119
  • 1
  • 13
  • 40
0

Standard function is not binded to component, try arrow function:

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