[英]How to use all functions vue-auth without using its login function
我是 VueJS 的新手,正在尝试为我的网站构建授权功能。 首先我尝试使用库名Vue-auth来处理授权。 它工作正常,这是我的代码:
登录.vue
login () {
var redirect = this.$auth.redirect()
this.$auth.login({
headers: {
'Content-Type': 'application/json'
},
data: this.data.body,
rememberMe: this.data.rememberMe,
redirect: {name: redirect ? redirect.from.name : 'Home'},
success (res) {
console.log('Auth Success')
},
error (err) {
console.log(err)
}
导航栏():
<div class="nav-right is-flex">
<router-link v-if="!$auth.check()" to="/login" class="nav-item">Login</router-link>
<a v-if="$auth.check()" @click="logout" class="nav-item">Logout</a>
</div>
在路由器中,为了限制访问,我使用了 auth 属性。 就像是:
{
path: '/users',
name: 'users',
component: require('./components/pages/Users.vue'),
meta: {auth: ['admin']}
},
{
path: '/users',
name: 'users',
component: require('./components/pages/Users.vue'),
meta: true
}
在 app.js 中:
Vue.use(VueAuth, {
auth: {
request: function (req, token) {
this.options.http._setHeaders.call(this, req, {Authorization: 'Bearer ' + token})
},
response: function (res) {
// Get Token from response body
return res.data
}
},
http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
loginData: { url: 'http://localhost:6789/login', fetchUser: false },
refreshData: { enabled: false }
})
但是现在我想自己写一个服务来调用 axios 到 API Url,不再使用 $auth.login 函数。 我改变了我的
login () {
var self = this;
_AuthenticationService
.login(this.data.body)
.then(response => {
self.info = response;
console.log(response);
})
.catch(err => {
self.info = err;
});
我的服务:
import axiosconfigurator from '../axiosconfigurator'
class AuthenticationService {
login (request) {
var self = this
return new Promise((resolve, reject) => {
axios.post('https://reqres.in/api/login', {
username: 'Fred',
password: '123'
})
.then(function (response) {
// get token from this response
var token = response.data.token
self._setAuthToken(token, true)
console.log(token)
// var data = core.Parsers.UserParser.parse(response);
// history.update(data);
// deferred.resolve(history);
})
.catch(function (error) {
console.log(error)
reject(error)
});
})
}
所以我的问题是:我不想再使用 vue-auth 库登录功能,但我仍然想使用它的优点,比如 $auth.ready 函数,或者路由器和 $auth.user 中的 auth 属性。 我怎样才能实现它?
根据您提出问题的日期以及该库最近更改的事实您可以通过以下选项调用 vue-auth 对象上的登录方法
makeRequest:false
你在那里描述了一个解决方案https://github.com/websanova/vue-auth/issues/256
this.$auth.watch.authenticated = true
this.$auth.watch.loaded = true
this.$user(response.user)
this.$router.push('/dashboard')
我测试了它但它不起作用所以我打开了一张票https://github.com/websanova/vue-auth/issues/563
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.