M
M
mazahaler2019-10-11 13:30:20
JavaScript
mazahaler, 2019-10-11 13:30:20

How to use $this where it is undefined?

Hello, how can you use $this without resorting to declaring a variable through var in this case?

methods: {
            login() {
                var redirect = this.$auth.redirect() // ВОТ ЭТО МОЗОЛИТ ГЛАЗА ОЧЕНЬ СИЛЬНО
                var app = this // И ВОТ ЭТО
                this.$auth.login({
                    params: {
                        email: app.email,
                        password: app.password
                    },
                    success: function () {
                        // handle redirection
                        const redirectTo = redirect ? redirect.from.name : this.$auth.user().role === 2 ? 'admin.dashboard' : 'dashboard'
                        this.$router.push({name: redirectTo})
                    },
                    error: function (error) {
                        app.has_error = true
                        app.errors = error.response.data.errors || {}
                        app.error = error.response.data.error
                    },
                    rememberMe: app.remember_me,
                    fetchUser: true
                })
            },
         ........
        }

Is there a way to pass $this inside this.$auth.login without using var?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2019-10-11
@mazahaler

Use arrow functions

methods: {
    login() {
        this.$auth.login({
            params: {
                email: this.email,
                password: this.password
            },
            success: () => {
                // handle redirection
                const redirectTo = this.$auth.redirect()
                    ? this.$auth.redirect().from.name
                    : this.$auth.user().role === 2
                        ? 'admin.dashboard'
                        : 'dashboard'
                this.$router.push({name: redirectTo})
            },
            error: error => {
                this.has_error = true
                this.errors = error.response.data.errors || {}
                this.error = error.response.data.error
            },
            rememberMe: this.remember_me,
            fetchUser: true
        })
    },
    ........
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question