我想知道如何有条件地禁用VueRouter中的路由,以便不再访问它了!
我尝试使用this.$router.replace('/')
重定向,但网址确实显示了我想要跳过的路线。
有什么想法吗?
修改
这是我的VUEX商店:看看router.replace('/')
const store = new Vuex.Store({
state: {
users: [ ],
friendships: [ ],
userID: null
},
mutations: {
signUp(state, payload) {
auth.createUserWithEmailAndPassword(payload.email, payload.password).then((user) => {
if (user !== null) {
state.userID = user.uid
router.replace('/')
}
else {
state.userID = null
}
})
},
signIn(state, payload) {
auth.signInWithEmailAndPassword(payload.email, payload.password).then((user) => {
if (user !== null) {
state.userID = user.uid
router.replace('/')
}
else {
state.userID = null
}
})
},
signOut(state) {
auth.signOut()
state.userID = null
router.replace('/signin')
},
authenticate(state) {
auth.onAuthStateChanged((user) => {
if (user !== null) {
state.userID = user.uid
router.replace('/')
}
else {
state.userID = null
}
})
}
},
actions: {
signUp({ commit }) {
commit('signUp')
},
signIn({ commit }) {
commit('signIn')
},
signOut({ commit }) {
commit('signOut')
},
authenticate({ commit }) {
commit('authenticate')
},
redirect({ commit }) {
commit('redirect')
}
}
})
这是我的组件:
<template>
<div id="you">
<h1>you</h1>
<p>You are on your secret page!</p>
<p>{{ $store.state.userID }}</p>
</div>
</template>
<script>
export default {
name: 'you',
beforeCreate() {
if (this.$store.state.userID === null) {
this.$router.replace('/signin')
}
}
}
</script>
答案 0 :(得分:6)
您可以将a meta feild添加到您想要有条件地禁用它的路线上,如下所示:
export const routes = [
{path: '/', component: foo},
{path: '/bar', component: bar, meta:{conditionalRoute:true}}
];
在main.js中使用router.beforeEach
:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.conditionalRoute)) {
// this route requires condition to be accessed
// if not, redirect to home page.
if (!checkCondition) {
//check codition is false
next({ path: '/'})
} else {
//check codition is true
next()
}
} else {
next() // make sure to always call next()!
}
})
或者在该路线的组件上本地使用beforeRouteEnter()
navigation guard
beforeRouteEnter(to, from, next){
next(vm => {
// access to component instance via `vm`
if((checkCondition){
next();
}else{
next('/');
}
})
}
在您的登录组件中
beforeRouteEnter(to, from, next){
next(vm => {
// access to component instance via `vm`
if((vm.$store.state.userUID !== null){
next('/');
}else{
next();
}
})
}
答案 1 :(得分:-1)
在您的路线中,您可以使用navigation guard检查路线是否与您要禁用的路线匹配,然后使用return
而不是执行next()
router.beforeEach(to, from, next) {
if (to.path === "yourRoute") {
return;
}
}