我使用 vue.js.
当用户直接键入 url('/question') 并单击按钮但没有值时,我想防止访问没有某些值(questionNo)的页面。
main.vue
function buttonClickFunc(Num) {
return route.push({
name: 'question',
state: { questionNo: Num }
})
};
router.js
// ...
{
path: '/question',
name: 'question',
beforeEnter: (to, from, next) => {
if(!history.state.questionNo) { // there is no questionNo
next('/main');
} else {
next();
}
}
}
我在使用router.push时不使用
query
而是state
。
因为 url 需要是 '/question' 而不是 'question=?questionNo=14'。
并且如果使用
params
,控制台工具中会出现[Vue Router warn]消息。
警告链接
在router push之前有办法检查questionNo exist,但是不能阻止直接输入url。
请看下面的代码修改。它可能对你有帮助。
main.vue
function buttonClickFunc(Num) {
return route.push({
name: 'question',
params: { question: Num }
})
};
route.js
{
path: '/question/:questionNo',
name: 'question',
beforeEnter: (to, from, next) => {
if(!to.params.questionNo) { // there is no questionNo
next('/main');
} else {
next();
}
}
}
希望这对你有帮助。