我是VueJS的新手,正在尝试为我的网站建立授权功能。首先,我尝试使用库名Vue-auth来处理授权。它工作得很好,下面是我的代码:
Login.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)
}navbar ():
<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,而不再使用$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属性。我怎样才能做到这一点?
发布于 2020-06-03 20:44:06
根据您提出问题的日期和库最近被更改的事实,您可以调用vue-auth对象上的login方法,传递以下选项
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
https://stackoverflow.com/questions/50509680
复制相似问题