首页 > 解决方案 > 如何在 Vue 中从外部回调中设置数据?

问题描述

我在组件中包含了一些外部 SDK:

mounted() {
    // Load external Script
    let externalScript = document.createElement('script')
    externalScript.setAttribute('src', 'https://x.klarnacdn.net/kp/lib/v1/api.js')
    document.head.appendChild(externalScript)
    ...

后来我收到这样的回调:

authorizeKlarna: function(){  
        Klarna.Payments.authorize({
        payment_method_category: "pay_later"
        }, function(res) {
        console.debug(res);
        if(res.approved == true){ 
            this.token = res.authorization_token
        }
        })
      },

但是this.token不会更新,因为我超出了范围。有什么简单的方法可以从这个外部回调中访问我的 vue 组件的数据吗?

标签: vue.jsvuejs2vue-component

解决方案


尝试改变你function(res)的箭头功能(res) =>

authorizeKlarna: function(){  
  Klarna.Payments.authorize(
  { payment_method_category: "pay_later" },
  (res) => {
    console.debug(res);
    if(res.approved == true){ 
      this.token = res.authorization_token
    }
  }
)
},

推荐阅读