【问题标题】:How to access data fields in Vue from async method? [duplicate]如何从异步方法访问 Vue 中的数据字段? [复制]
【发布时间】:2021-11-10 07:51:18
【问题描述】:

代码:

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

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

如何在 Vue 3 中处理来自异步方法的字段?

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    错误是由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();
        }, 
    },
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 2018-11-03
        • 2020-03-27
        • 2023-02-11
        相关资源
        最近更新 更多