如何访问vuejs中对象内的方法?

时间:2018-04-30 08:28:41

标签: javascript vuejs2

我正在尝试通过google文档在gov中登录,并且一切正常但我无法访问attachClickHandler中的方法。

new Vue({
    el: '#loginModal',
    data: { ...
    },
    methods: {
        gInit: function() {
            gapi.load('auth2', function() {
                auth2 = gapi.auth2.init({
                    client_id: 'MY-Client-id.apps.googleusercontent.com',
                    cookiepolicy: 'single_host_origin',
                    //scope: 'additional_scope'
                });
                auth2.attachClickHandler(document.getElementById('googleBtn'), {},
                    function(googleUser) {
                        const profile = googleUser.getBasicProfile();
                        const gplusObj = {
                            name: profile.getName(),
                            email: profile.getEmail(),
                            provider: 'google',
                            image: profile.getImageUrl(),
                            provider_user_id: profile.getId()
                        };

                        this.socialLogin(gplusObj);
                    },
                    function(error) {
                        alert(JSON.stringify(error, undefined, 2));
                    });
            });
        },
        socialLogin: function(data) {
            axios.post(`${this.api}/api/sociallogin`, data)
                .then(res => {
                    console.log(res);
                }).catch(err => {
                    console.log(err);
                });
        },
    },
    mounted: function() {
        this.gInit();
    }

})

此处调用socialLogin()内的函数attachClickHandler(),但未定义错误this.socialLogin is not a function。为什么这不起作用?

2 个答案:

答案 0 :(得分:2)

这是因为this.socialLogin调用位于回调函数中。此函数创建一个新的上下文,以便this更改,不再是您的组件。 使用箭头功能。他们不会改变this

编辑:更改您的代码:

gInit() {
    gapi.load('auth2', () => {
        ...
        auth2.attachClickHandler(document.getElementById('googleBtn'), {}, (googleUser) => {
            ...
            this.socialLogin(gplusObj);
        }, (error) => {
            alert(JSON.stringify(error, undefined, 2));
        });
    });
},

有关该主题的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions,请参阅“此单独”。

答案 1 :(得分:0)

因为您没有保存this,请尝试:



new Vue({
  el: '#loginModal',
  data: { ...
  },
  methods: {
    gInit: function() {
      let self = this // new added
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
          client_id: 'MY-Client-id.apps.googleusercontent.com',
          cookiepolicy: 'single_host_origin',
          //scope: 'additional_scope'
        });
        auth2.attachClickHandler(document.getElementById('googleBtn'), {},
          function(googleUser) {
            const profile = googleUser.getBasicProfile();
            const gplusObj = {
              name: profile.getName(),
              email: profile.getEmail(),
              provider: 'google',
              image: profile.getImageUrl(),
              provider_user_id: profile.getId()
            };
            console.log(e);
            self.socialLogin(gplusObj); //updated
          },
          function(error) {
            alert(JSON.stringify(error, undefined, 2));
          });
      });
    },
    socialLogin: function(data) {
      axios.post(`${this.api}/api/sociallogin`, data)
        .then(res => {
          console.log(res);
        }).catch(err => {
          console.log(err);
        });
    },
  },
  mounted: function() {
    this.gInit();
  }

})




this不会自动传递,你应该在学习vue之前就已经知道了。

此外,您可以使用arrow function来避免this被更改:



new Vue({
  el: '#loginModal',
  data: { ...
  },
  methods: {
    gInit: function() {
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
          client_id: 'MY-Client-id.apps.googleusercontent.com',
          cookiepolicy: 'single_host_origin',
          //scope: 'additional_scope'
        });
        auth2.attachClickHandler(document.getElementById('googleBtn'), {},
          (googleUser) => { //updated
            const profile = googleUser.getBasicProfile();
            const gplusObj = {
              name: profile.getName(),
              email: profile.getEmail(),
              provider: 'google',
              image: profile.getImageUrl(),
              provider_user_id: profile.getId()
            };
            console.log(e);
            this.socialLogin(gplusObj);
          },
          function(error) {
            alert(JSON.stringify(error, undefined, 2));
          });
      });
    },
    socialLogin: function(data) {
      axios.post(`${this.api}/api/sociallogin`, data)
        .then(res => {
          console.log(res);
        }).catch(err => {
          console.log(err);
        });
    },
  },
  mounted: function() {
    this.gInit();
  }

})