【问题标题】:VueJS this.progress is undefined inside window functionVueJS this.progress 在窗口函数中未定义
【发布时间】:2021-12-14 09:39:42
【问题描述】:

我正在使用 Facebook 登录,并且我正在为用户显示加载进度,直到我收到 Facebook 的回复以进行身份​​验证。 但是我曾经像this.progress = false一样隐藏进度条但是这个变量在窗口函数中是未定义的。

我的代码:

initFacebook() {
    this.progress=true
      window.fbAsyncInit = function() {
        window.FB.init({
          appId: "MY-APP-ID", //You will need to change this
          cookie: true, // This is important, it's not enabled by default
          version: "v2.6",
          status: false,
        });
        
        window.FB.login(function(response) {
          
        if (response.status === 'connected'){

        window.FB.api('/me?fields=id,name,email', function(response) {
        console.log( response) // it will not be null ;)
    })
     
        } else {
          console.log("User cancelled login or did not fully authorize.")         

        }

      },
      
      {scope: 'public_profile,email'}
      );
    this.progress = false
console.warn(this.progress)

      };

    },

在收到 Facebook 的所有回复后,我无法设置 this.progress = false。

我在 console.log(this.progress) 变量时遇到错误。

错误:

Login.vue?7463:175 undefined

身份验证检查完成后,如何将 this.progress 变量设置为 false?

【问题讨论】:

标签: javascript vue.js vuejs2 vuejs3


【解决方案1】:

尝试将所有 function() 调用转换为箭头函数调用 () =>

问题是function() 会破坏全局vue 作用域。所以 vue thisfunction() 调用中不可用,但在箭头函数 () => {} 中可用

在块作用域(function() { 语法)中, this 绑定到嵌套作用域,而不是 vue 的 this 实例。如果您想将 vues this 保留在函数中,请使用箭头函数(ES6),或者您可以使用 const that = this 并将全局 this 推迟到常规 function() { 如果您喜欢这种方式。

尝试使用这个用箭头函数转换的代码,看看它是否有效:

initFacebook() {
  this.progress=true
    window.fbAsyncInit = () => {      
      window.FB.init({
        appId: "MY-APP-ID", //You will need to change this
        cookie: true, // This is important, it's not enabled by default
        version: "v2.6",
        status: false,
      });

      window.FB.login((response) => {            
        if (response.status === 'connected'){
          window.FB.api('/me?fields=id,name,email', (response) => {
            console.log( response) // it will not be null ;)
          })     
        } else {
          console.log("User cancelled login or did not fully authorize.")
        }
      },      
    {scope: 'public_profile,email'});
    this.progress = false
    console.warn(this.progress)
  };
},

我知道这一点是因为我也遇到了同样的问题 :-) 请参见此处: Nuxt plugin cannot access Vue's 'this' instance in function blocks

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2021-05-07
    • 2017-10-01
    • 2019-07-01
    • 2017-03-17
    • 2021-02-02
    • 2016-07-24
    • 2021-10-06
    相关资源
    最近更新 更多