2017-04-09 72 views
0

我試圖在我的應用中使用vue-authenticate,但是我在使用插件方法時遇到了一些問題。這個插件依賴於vue-resource,所以第一步是安裝這兩個軟件包。該插件沒有在VueJS中激活

main.js文件,我導入並激活兩個包,其中包括本地認證的具體配置:現在

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' 
}) 

,在我登錄組件,命名Login,創建一個方法,稱爲aLogin到避免名稱衝突:

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

在這種組件,credenciales是一個對象,在定義有兩個屬性,usernamepassword。在submit事件中調用方法aLogin

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

但是什麼都沒有發生,並且在控制檯中有這個。

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) 

爲什麼this.$authundefined如果在main.js已經註冊?如何正確激活它?

在此先感謝。

回答

2

不是在Vue中用胖箭頭函數定義了一個方法。如果你這樣做,this不會引用Vue實例。

嘗試

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

VueJS: why is 「this」 undefined?

+0

不,它不是'window'。它是組件類(或者你喜歡的構造函數)。 – Leo

+0

@leo在這種情況下,你是對的,它不是窗口。它是封閉的範圍或未定義的。但是,這不是類或構造函數。 – Bert