该插件在VueJS中无法激活

时间:2017-04-09 03:47:27

标签: vuejs2 vue-component

我尝试在我的应用中使用vue-authenticate,但是我使用插件时出现了一些问题'方法。这个插件具有依赖vue-resource,因此第一步是安装两个包。

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是一个对象,在data()中定义,包含两个属性usernamepassword。方法aLoginsubmit事件中以表格形式调用。

<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.$auth已在undefined中注册,为什么main.jsfor-each?如何正确激活它?

提前致谢。

1 个答案:

答案 0 :(得分: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?