I wonder how to disable a route in VueRouter conditionally, so that it can't be accessed anymore!
I tried to redirect with this.$router.replace('/')
but the URL did show the route that I wanted to skip.
Any thoughts?
EDIT:
this is my VUEX-Store: Have a look at 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')
}
}
})
and here is my component:
<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>
You can add a meta feild to that route you want to conditionally disable it like this:
export const routes = [
{path: '/', component: foo},
{path: '/bar', component: bar, meta:{conditionalRoute:true}}
];
And use router.beforeEach
in your main.js :
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()!
}
})
Or else use beforeRouteEnter()
navigation guard locally on that route's component
beforeRouteEnter(to, from, next){
next(vm => {
// access to component instance via `vm`
if(checkCondition){
next();
}else{
next('/');
}
})
}
In your signin component
beforeRouteEnter(to, from, next){
next(vm => {
// access to component instance via `vm`
if(vm.$store.state.userUID !== null){
next('/');
}else{
next();
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With