我想知道如何有条件地禁用VueRouter中的路由,以便它不再被访问!
我尝试重定向,this.$router.replace('/')但URL确实显示了我想要跳过的路线.
有什么想法吗?
编辑:
这是我的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')
}
}
})
Run Code Online (Sandbox Code Playgroud)
这是我的组成部分:
<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>
Run Code Online (Sandbox Code Playgroud)
您可以将meta feild添加到您想要有条件地禁用它的路由,如下所示:
export const routes = [
{path: '/', component: foo},
{path: '/bar', component: bar, meta:{conditionalRoute:true}}
];
Run Code Online (Sandbox Code Playgroud)
并router.beforeEach在你的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()!
}
})
Run Code Online (Sandbox Code Playgroud)
或者在该路线的组件上本地使用beforeRouteEnter() 导航防护
beforeRouteEnter(to, from, next){
next(vm => {
// access to component instance via `vm`
if((checkCondition){
next();
}else{
next('/');
}
})
}
Run Code Online (Sandbox Code Playgroud)
在您的登录组件中
beforeRouteEnter(to, from, next){
next(vm => {
// access to component instance via `vm`
if((vm.$store.state.userUID !== null){
next('/');
}else{
next();
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9194 次 |
| 最近记录: |