0

I tried to use vue-authenticate in my app, but I've some problems using the plugins' methods. This plugin has as dependency vue-resource, so the first step is installing both packages.

The in main.js file, I import and activate both packages, including the specific configuration for local authentication:

import Vue from 'vue'
import VueResource from 'vue-resource'
import VueAuthenticate from 'vue-authenticate'
// ...
Vue.use(VueResource)
Vue.use(VueAuthenticate, {
  baseUrl: 'http://sgc-server.dev',
  tokenType: 'Token'
})

Now, in my login component, named Login, create a method, called aLogin to avoid name conflicts:

// ...
methods: {
  aLogin: (_credenciales) => {
    this.$auth.login(_credenciales).then((_carga) => {
      // Ejecutamos la lógica que sigue a un login exitoso
      console.log(_carga)
    })
  }
} 
// ..

In this component, credenciales is an object, defined in data() with two properties, username and password. The method aLogin is called in a form on submit event.

<form class="form" @submit.prevent="aLogin(credenciales)">

But nothing happen, and have this in the console.

Login.vue?8031:64 Uncaught TypeError: Cannot read property 'login' of undefined
    at VueComponent.aLogin (eval at <anonymous> (app.js:1987), <anonymous>:18:18)
    at Proxy.boundFn (eval at <anonymous> (app.js:735), <anonymous>:125:14)
    at submit (eval at <anonymous> (app.js:7875), <anonymous>:21:13)
    at HTMLFormElement.invoker (eval at <anonymous> (app.js:735), <anonymous>:1657:18)

Why the this.$auth is undefined if it is already registered in main.js? How can activate it properly?

Thanks in advance.

toledano
  • 289
  • 11
  • 20

1 Answers1

2

Do not define a method in Vue with a fat arrow function. If you do that, this does not refer to the Vue instance.

Try

methods: {
  aLogin: function(_credenciales){
    this.$auth.login(_credenciales).then((_carga) => {
      // Ejecutamos la lógica que sigue a un login exitoso
      console.log(_carga)
    })
  }
}

See VueJS: why is “this” undefined?

Bert
  • 80,741
  • 17
  • 199
  • 164
  • No, it's not `window`. It's the component class (or constructor if you prefer). – Leo Sep 22 '17 at 14:10
  • @leo You're right in this case that it's not the window. It's the enclosing scope or undefined. But, it's not the class or constructor. – Bert Sep 22 '17 at 14:49