如何将VueJS方法范围绑定到Firebase Promise

时间:2017-09-21 07:52:37

标签: javascript firebase vue.js firebase-authentication

如何将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'

1 个答案:

答案 0 :(得分: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);
                })
        }