当我使用vue路由器导航时,一切正常。例如:我使用@ click = login()单击按钮。在登录方法上方
methods: {
login () {
this.$router.push('/admin')
}
因此,vue将用户重定向到“ / Admin”页面,并且路由器调用beforeEach事件,在该事件中,我检查页面是否具有用于验证用户访问权限的元属性
然后在我的router / index.js
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
Routes
]
})
router.beforeEach(async (to, from, next) => {
if (to.meta.requiresAdminAuth) {
let app = router.app.$data || {isAuthenticated: false}
if (app.isAuthenticated) {
// already signed in, we can navigate anywhere
next()
} else if (to.matched.some(record => record.meta.requiresAdminAuth)) {
// authentication is required. Trigger the sign in process, including the return URI
console.log(router.app.hello)
let authenticate = router.app.authenticate
authenticate(to.path).then(() => {
console.log('authenticating a protected url:' + to.path)
next()
})
} else {
// No auth required. We can navigate
next()
}
} else {
next()
}
})
要验证用户,我使用全局方法,此方法有效。但是,当用户从URL(而不是从我的按钮)导航到“ / Admin”时,全局变量未定义。所以我尝试使用Mixin,但是结果是一样的。
这是我的main.js,在其中指定全局方法和mixin:
var myMixin = {
methods: {
hello: function () {
console.log('Bem-vindo ao mixin!')
}
}
}
const globalData = {
isAuthenticated: false,
user: '',
mgr: mgr
}
const globalMethods = {
async authenticate (returnPath) {
const user = await this.$root.getUser()
if (user) {
this.isAuthenticated = true
this.user = user
} else {
await this.$root.signIn(returnPath)
}
},
async getUser () {
try {
let user = await this.mgr.getUser()
console.log(user)
return user
} catch (err) {
console.log(err)
}
},
signIn (returnPath) {
returnPath ? this.mgr.signinRedirect({ state: returnPath })
: this.mgr.signinRedirect()
}
}
/* eslint-disable no-new */
new Vue({
mixins: [myMixin],
el: '#app',
router,
store,
template: '<App/>',
components: { App },
data: globalData,
methods: globalMethods
})
我该怎么做?用户通过URL导航时执行已定义的方法?