【问题标题】:How to bind VueJS methods scope to Firebase Promise如何将 VueJS 方法范围绑定到 Firebase Promise
【发布时间】:2018-03-02 11:27:39
【问题描述】:

如何将 VueJs 方法范围绑定到返回的 Firebase Promise?为了调用 VueJS Modal

   login: function () {
            fireAuth.signInWithEmailAndPassword(this.signIn.email, this.signIn.password)
                .then(function (user) {
                    if (!user.emailVerified) {
                        this.$modal.show('email_verification', {
                            text: 'Please verify your email'
                        })
                    }
                }, function (error) {
                    console.log(error.message);
                })
        }

现在,这里出现错误:

TypeError: 无法读取未定义的属性“$modal”

【问题讨论】:

    标签: javascript firebase vue.js firebase-authentication


    【解决方案1】:

    在你的 Promise 回调中使用箭头函数,以便 this 被词法绑定

    login: function () {
                fireAuth.signInWithEmailAndPassword(this.signIn.email, this.signIn.password)
                    .then( (user) => {
                        if (!user.emailVerified) {
                            this.$modal.show('email_verification', {
                                text: 'Please verify your email'
                            })
                        }
                    },  (error) => {
                        console.log(error.message);
                    })
            }
    

    或者声明一个 var self 指向方法内的 vue 实例并使用 self 来使用 vue 实例,因为回调现在将在 var self 变量上具有一个闭包

    login: function () {
               var self = this;
                fireAuth.signInWithEmailAndPassword(this.signIn.email, this.signIn.password)
                    .then(function (user) {
                        if (!user.emailVerified) {
                            self.$modal.show('email_verification', {
                                text: 'Please verify your email'
                            })
                        }
                    }, function (error) {
                        console.log(error.message);
                    })
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2018-01-28
      • 2017-09-24
      • 1970-01-01
      相关资源
      最近更新 更多