Vue:在函数内丢失“ this”的上下文

时间:2019-03-25 00:19:40

标签: vue.js

我在Promise的“ then”部分中丢失了此上下文。我标记了第一个调试器,当我输入this时,该调试器将值显示为Vue组件。我继续,当我在Promise的then部分中单击下一个调试器语句时,即使使用胖箭头语法,this的值也未定义。

父组件

<Modal
    @emitshowflashmsg="handleShowCouponModal"
>

子组件(Modal.vue

methods: {

  showFlash: function(msg, bool) {
    let data = {msg, bool}
    this.$emit('emitshowflash', data)
  },

  updateShippingAddress: function() {

    debugger
    // `this` has a value here
    axios.post('/api/act/address', { 
        street_address: this.$refs.streetAddress.value ? this.$refs.streetAddress.value : "",
        apartment: this.showSecondAddressLine ? this.$refs.apartment.value : "",
        city: this.$refs.city.value ? this.$refs.city.value : "",
        state: this.$refs.state.value ? this.$refs.state.value : "",
        zip: this.$refs.zip.value ? this.$refs.zip.value : ""
    })

    .then((response) => {
        debugger
        // `this` is undefined here
        if(response.data.success) {
            let msg = "Address updated!"
            this.showFlash(msg, true)
        }
    })
    .catch(err => {
        console.log("errrrr")
        let msg = "Not valid address. Please check address again."
        this.showFlash(msg, true)

    });
  }
}

0 个答案:

没有答案