是之前博客写的前端路由,是基于原生WebAPI手动搭建的前端路由。在Vue框架中,Vue官方提供了相应的路由管理器,即VueRouter。不管是哪种前端路由管理工具,实现思路基本都是一样的。因此,在学习如何使用VueRouter时,应该从路由表、路由链接、路由内容等方面记住。1、什么是VueRouter,是vue.js官方的路由管理器。2.基本使用2.1安装vue-router在项目中安装:yarnaddvue-router导入:importVueRouterfrom'vue-router'Vue.use(VueRouter)2.2定义路由表constroutes=[{path:'/a',component:A},{path:'/b',component:B}]2.3创建VueRouter实例constrouter=newVueRouter({routes,mode:'history'//路由模式选择,默认为hash})2.4将路由注入applicationnewVue({render:h=>h(App),router}).$mount('#app')2.5定义路由交叉点(一个链接位置)转到A转到B2.6定义路由出口(内容显示位置)2.7定义默认路由和404路由constroutes=[//defaultroute,match/{path:'/',component:A},{path:'/a',component:A},{path:'/b',component:B},//使用通配符放在路由表末尾匹配404路由{path:'*',component:NotFound}]3.VueRouter实例Af的使用在将VueRouter实例路由器注入到Vue应用程序之后,VueRouter在内部做了一些操作,在Vue的原型上定义了路由器实例相关的信息,以便所有Vue组件都可以访问路由器实例。$router:创建的路由实例,包含所有路由信息$route:当前路由信息对象4.动态路由,在路由表前添加path属性参数:constroutes=[{path:'/',component:B},//动态路由{path:'/a/:id',component:A},{path:'/b',component:B},{path:'*',component:NotFound}]这种方式,/a/1和/a/2都会显示组件A//A.vue我是A组件的内容,我收到的参数是{{$route.params.id}}
5.嵌套路由在每个路由中配置VueRouter将子属性添加到对象以进行嵌套路由。用法如下:constroutes=[{path:'/',component:A,children:[{path:'',component:A0},]},{path:'/a',component:A,children:[//匹配的''空白字符是指url为/a时A.vue中RouterView显示的内容{path:'',component:A0},{path:'1',component:A1},{path:'2',component:A2}]},{path:'/b',component:B},{path:'*',component:NotFound}]//A.vue我是A组件的内容转到A1转到A2