很多时候我们需要将给定匹配模式的路由映射到同一个组件: 例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但是用户的 ID 是不同的; 在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数;
// 映射表
{path:'/user/:id',component:()=>import('../pages/User.vue')
}
router-link 跳转
User 中如何获取到对应的值呢 在 template 中,直接通过 $route.params 获取值;
用户界面 {{$route.params.id}}
export default {
created() {console.log(this.$route.params.id)
},
setup() {const route = useRoute()console.log(route)console.log(route.params.id)
}
// 映射表
{path:'/user/:id/:info',component:()=>import('../pages/User.vue')
}
this.$route.params => {id:'xxx',info:'yyy'}
对于哪些没有匹配到的路由,我们通常会匹配到固定的某个页面 比如 NotFound 的错误页面中,这个时候我们可编写一个动态路由用于匹配所有的页面;
// 映射表
{path:'/:pathMatch(.*)',component:()=>import('../pages/User.vue')
}
$route.params.pathMatch
Not Found: [ "user", "hahah", "123"] => path:'/:pathMatch(.*)*",
Not Found: user/hahah/123 => path:'/:pathMatch(.*)",
目前我们匹配的 Home、About、User 等都属于底层路由,我们在它们之间可以来回进行切换; 但是呢,我们 Home 页面本身,也可能会在多个组件之间来回切换:
这个时候我们就需要使用嵌套路由,在 Home 中也使用 router-view 来占位之后需要渲染的组件;
{
path: '/home',
component:()=> import(/* webpackChunkName:"home-chunk "*/"./pages/Home.vue"),
children:[{path:redirect: "/home/product'},{path:'product',component: ()=> import('../pages/HomeProduct.vue")},{ path:'message', component: ()=>import('../pages/HomeMessage.vue")}
],
}
使用 push 的特点是压入一个新的页面,那么在用户点击返回时,上一个页面还可以回退,但是如果我们希望当前 页面是一个替换操作,那么可以使用 replace
jumpToProfile(){// 直接传入值this.$router.push('/profile')// 传入一个对象this.$router.push({path:'/profile'})
}
const router = useRouter()
const jumpToProfile = router.replace('/profile")
jumpToProfile() {this.$router.push(path: "/profile",query:{ name:"why", age: 18 }})
}
在界面中通过 $route.query 来获取参数:
query: {{ $route.query.name }}-{{ $route.query.age }}
// 向前移动一条记录,与 router.forward() 相同
router.go(1)
// 返回一条记录,与router.back()• 相同
router.go(-1)
// 前进3 条记录
router.go(3)
// 如果没有那么多记录,静默失败
router.go(-100)
router.go(100)
通过调用 history.back() 回溯历史。相当于 router.go(-1);
通过调用 history.forward() 在历史中前进。相当于 router.go(1);
在 vue-router3.x 的时候,router-link 有一个 tag 属性,可以决定 router-link 到底渲染成什么元素: 但是在 vue-router4.x 开始,该属性被移除了;
<- @click="navigate">跳转about
href: {{ href }}
route: {{ route }}
isActive: {{ isActive}}
isExactActive: {{ isExactActive }}
router-view 也提供给我们一个插槽,可以用于 和 组件来包裹你的路由组件:
某些情况下我们可能需要动态的来添加路由:
如果我们是为 route 添加一个 children 路由,那么可以传入对应的 name: 动态添加一个路由
const categoryRoute = { path:'/category', component: () => import ('../pages/Category.vue')
}
router.addRoute(categoryRoute)
const categoryRoute = { path:'/home', component: () => import ('../pages/Category.vue')
}
router.addRoute('home', homeMomentRoute)
方式一:添加一个 name 相同的路由;
router.addRoute({ path: '/about' name: "about",component: About}
// 这将会删除之前己经添加的路由,因为他们具有相同的名字且各字必须是唯一的
router.addRoute({ path: '/other' name: "about",component: About}
方式二:通过 removeRoute 方法,传入路由的名称;
router.addRoute({ path: '/about' name: "about",component: About})
// 删除路由如果存在的话
router.removeRoute('about')
方式三:通过 addRoute 方法的返回值回调
const removeRoute = router.addRoute({ path: '/about' name: "about",component: About}
removeRoute()
let Vue;
class VueRouter {constructor(options) {this.$options = options;this.routerMap = {};this.app = new Vue({data: {current: "/",},});}init() {this.bindEvent();// 初始化组件this.initComponent();// 做一个路由的映射关系表this.createRouteMap(this.$options);}bindEventListener(type) {const historyEvent = history[type];return function () {const newEvent = historyEvent.apply(this, arguments);const e = new Event(type);e.arguments = arguments;window.dispatchEvent(e);return newEvent;};}// 监听bindEvent() {// 刚刚进入页面的,页面改变了吗?没有的window.addEventListener("load", this.onHashChange.bind(this), false);window.addEventListener("hashchange", this.onHashChange.bind(this), false);history.pushState = this.bindEventListener("pushState");window.addEventListener("pushState", this.onHashChange.bind(this), false);}// 改变后的方法onHashChange() {console.log("当前的路由");this.app.current = window.location.hash.slice(1) || "/";}// 初始化组件initComponent() {// link我们需要他是一个链接Vue.component("router-link", {props: {to: String,},render(h) {// return {this.$slots.default};return h("a",{attrs: {href: "#" + this.to,},},[this.$slots.default]);},});Vue.component("router-view", {render: (h) => {let component = this.routerMap[this.app.current].component;return h(component);},});}createRouteMap(options) {options.routes.forEach((item) => {this.routerMap[item.path] = item;});console.log(this.routerMap);}
}
VueRouter.install = function (_Vue) {Vue = _Vue;Vue.mixin({beforeCreate() {if (this.$options.router) {Vue.prototype.$router = this.$options.router;// 确保只执行一次,并且初始化一次this.$options.router.init();}},});
};
export default VueRouter;