And*_*elt 3 javascript vue.js vue-router
在我的 Vue.js 项目中,如果路由参数无效,我想显示我的 404 页面。现在,我为此使用以下代码:
this.$router.replace({ path: '/404' });
Run Code Online (Sandbox Code Playgroud)
有没有办法在不修改 URL 的情况下做到这一点?我希望用户仍然能够复制浏览器的原始 URL 行。有某种silent: true参数吗?
NotFound像这样构建你的路线:
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: NotFound
},
Run Code Online (Sandbox Code Playgroud)
然后你可以beforeEnter在动态 Vue 上使用导航守卫,如下所示:
// In your router/index.js file...
{
path: 'users/:id',
name: 'User Detail',
component: UserDetail,
beforeEnter(to, from) {
// See if that query exists in your data...
const exists = data.users.find(
user => user.id === parseInt(to.params.id)
)
if (!exists) {
// THE IMPORTANT PART
// Return your not found view...
return {
name: 'NotFound',
// Match the path of your current page and keep the same url...
params: { pathMatch: to.path.split('/').slice(1) },
// ...and the same query and hash.
query: to.query,
hash: to.hash,
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
尚未在组件中对此进行测试,但我认为导航防护中的逻辑相同beforeRouteEnter。
使用vue-router,URL 是事实的来源。如果 URL 更改,渲染也会更改。你不能“暂停”路由器。(这是一个缺陷vue-router,多年来一直困扰着我,但我离题了。)
您只需要显示 404 页面而无需修改路由。display404在您的根组件中有一些数据属性,您可以将其设置为在模板中手动显示 404 页面而不是<router-view>,例如:
<div>
<my-404-page v-if="display404"/>
<router-view v-else/>
</div>
Run Code Online (Sandbox Code Playgroud)
要从任何组件显示 404 页面:
this.$root.display404 = true
Run Code Online (Sandbox Code Playgroud)
当然,这只是一个基本的例子来演示我的意思,你可能想使用 Vuex 来共享状态,或者使用事件总线,或者你可以以其他适合你的方式显示 404 页面,等等。