我正在为我的应用程序尝试websanova/vue-auth,我不知道如何实现这两件事:
登录后根据用户角色重定向
在我的Login.vue组件中,在this.$auth.login()中,我尝试像在docs (https://github.com/websanova/vue-auth/blob/master/docs/Methods.md#redirect)中一样使用this.$auth.redirect(),但是我不知道它是如何工作的,也不知道如何配置它,因为redirect.from.name不存在,console.log(this.$auth.redirect()返回null
我尝试像这样设置this.$auth.login()的this.$auth.login()参数:redirect: {name: this.$auth.user().role == 2 ? 'admin.dashboard' : 'dashboard'},,但是它不能工作,因为它总是重定向到仪表板。
在success()的this.$auth.login()方法中,我可以看到this.$auth.user().role等于2,但是我认为重定向是在用户被获取之前定义的.
下面是代码:
login(){
var app = this
var redirect = this.$auth.redirect()
this.$auth.login({
params: {
email: app.email,
password: app.password
},
success: function () {
console.log(this.$auth.redirect()) // null
console.log(this.$auth.user().role) // 2
},
error: function () {},
rememberMe: true,
// try 1
//redirect: {name: redirect ? redirect.from.name : 'dashboard'},
// try 2
redirect: {name: this.$auth.user().role == 2 ? 'admin.dashboard' : 'dashboard'},
fetchUser: true,
});
}根据用户的角色授予访问某些路由
我只想授予管理员访问管理仪表板的权限。根据文档,它可以这样做:auth: {roles: 'admin', redirect: '/admin/login', forbiddenRedirect: '/admin/403'}
但是它不起作用,我也不知道如何配置。
获取的用户有一个role属性,设置为2以进行管理。如何与roles所期待的值进行匹配?
谢谢
发布于 2018-08-13 22:42:57
好的,昨天我有点累了,我发现如何多读一些文档来解决我的问题;)
登录后根据用户角色重定向
让我们忘记,我完全误解了this.$auth.redirect()的目的(不是为了重定向,而是为了知道重定向是否正在进行:p )
因此,为了在登录后重定向用户的角色,我这样做了:
1/使用loginData选项防止vue-auth中的默认登录重定向
Vue.use(require('@websanova/vue-auth'), {
auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
loginData: {redirect: ''}
...
})2/句柄重定向在我的Login.vue组件中,在$auth.login()的success()回调中
this.$auth.login({
params: {
email: app.email,
password: app.password
},
success: function () {
// handle redirection
let redirectTo
if (redirect) {
redirectTo = redirect.from.name
} else {
redirectTo = this.$auth.user().role === 2 ? 'admin.dashboard' : 'dashboard'
}
this.$router.push({name: redirectTo})
},
error: function () {},
rememberMe: true,
fetchUser: true,
})根据用户的角色授予访问某些路由
我只是缺少了选项文档中的一个信息:rolesVar参数,用于告诉vue-auth用户的属性用于角色检查。
我的用户将role属性设置为常规用户的1和admins的2。
因此,我将rolesVar: 'role'添加到vue-auth选项中:
Vue.use(require('@websanova/vue-auth'), {
auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
loginData: {redirect: ''}
rolesVar: 'role',
...
})我的路线是这样的:
path: '/admin',
name: 'admin.dashboard',
component: AdminDashboard,
meta: {
auth: {roles: 2, redirect: {name: 'login'}, forbiddenRedirect: '/403'}
},我希望这会有帮助:)
https://stackoverflow.com/questions/51814309
复制相似问题