2017-07-02 85 views
0

我正在为我的Web应用程序构建custon社交登录页面,并且我遇到了一个无法找到原因的bug。无法更改Vue实例数据值

基本上,我想调用一个名为“connectFb”的函数,然后如果所有的Facebook API调用都成功了,我想在我的vue实例中更改一堆数据以渲染其他元素。 (那些通过V-如果有条件rendred)

这里是我的代码负责此部分:

app = new Vue({ 
    el : "#social-auth", 
    data: { 
     showTwitter : false, 
     showFb: true, 
     showPages: false, 
     fb_state: "unconnected", 
     continue_auth: false, 
     pages_fb: [] 
    }, 
    methods : { 
     connectFb: function() { 
    FB.login(function(response) { 
     if (response.authResponse) { 
     alert('You are logged in & cookie set!'); 
     fb_token = response.authResponse.accessToken 
     FB.api('/me/accounts','get',{access_token: fb_token},function(pages){ 
      if(pages["error"] !== undefined){ 
       console.log('EROR') 
      } 
      else{ 
       console.log("Got a list of pages"); 
       console.log(pages); 
       this.pages_fb = pages.data; 
       this.showFb = false; 
       this.showPages = true; 
       this.continue_auth = true; 
      } 
     }) 


     } else { 
     alert('User cancelled login or did not fully authorize.'); 
     } 
    },{scope: 'public_profile,manage_pages'}); 
    return false; 
    } 

如何代码工作:

基本上,用户登录后到fb,它会得到他的页面列表,这不是问题,问题是在成功回调它之后(与函数获取页面有关的回调)。使用调试器,我可以看到变量页面包含我需要的所有数据,而pages.data返回这些页面信息的数组。

在此之后,我试图将它归因于我的实例变量称为pages_fb。 当此代码运行时pages_fb始终为空,即使pages.data不是。

问题不仅在于pages_fb,而且在回调运行后,它们在回调中应该改变的所有实例变量都是相同的。

我对这个问题感到生气,所以请帮助我了解什么是错的。

回答

1

极其常见的错误。 this在您的FB.login回调中定义的不是Vue。使用箭头函数,关闭或bind使其正确。

FB.api('/me/accounts','get',{access_token: fb_token}, pages => { 
    ... 
}) 

How to access the correct this inside a callback?

+0

感谢对你的回答,你是对的,问题是用'this',我想指出,对于使用旧的浏览器,如我这样的人,你应该归结于这样'self'在更大的范围内,然后使用'self'而不是'this'。 –

+0

@AnisSouames使用'self'使用闭包,这是在答案:) – Bert

1

当你在它没有指向您的Vue的实例了回调使用this.。您可以使用=>函数以您想要的方式进行绑定。试试这个:

FB.api('/me/accounts','get',{access_token: fb_token},(pages) => { 
     if(pages["error"] !== undefined){ 
      console.log('EROR') 
     } 
     else{ 
      console.log("Got a list of pages"); 
      console.log(pages); 
      this.pages_fb = pages.data; 
      this.showFb = false; 
      this.showPages = true; 
      this.continue_auth = true; 
     } 
    })