在使用 Vue-Router 作为路由组件开发应用程序时,如果用户输入的URL路由地址是我们没有的,则此时默认系统将返回404错误;但是,这不是友好的,我们需要对所有没有匹配到的路由地址提供一个默认的路由地址。如:Default.vue 等。
幸运的是 Vue-Router 组件提供了通配符(*)。实例如下:
// 会匹配以 `/user-` 开头的任意路径
{path: '/user-*'}
// 会匹配所有路径
{ path: '*'}当使用通配符路由时,请确保路由的顺序是正确的,也就是说含有通配符的路由应该放在最后。
当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分:
// 给出一个路由 { path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
// 给出一个路由 { path: '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'实例:用户在访问/user1、/user2等等,以/user开头的路由时,将使用User组件进行渲染。/test、/none等完全不存在的路由地址时,将使用Default组件进行渲染。代码如下:
Default.vue
<template>
<div class="default">
<h2>Default Page</h2>
<p>default page content</p>
</div>
</template>
<script>
export default {
name: "Default"
}
</script>
<style scoped></style>index.js
import Vue from 'vue'
// 引入路由
import Router from 'vue-router'
// 导入自己的组件
import User from '@/components/User'
import Default from '@/components/Default'
// 使用路由
Vue.use(Router)
export default new Router({
routes: [
{path: '/user-*', component: User},
{path: '*', component: Default}
]
})