vue-router
1.router-link与router.push
<router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link>router-link可以在不重新加载页面的情况下更改URL,处理URL以及编码
声明式导航
<router-link :to="...">等同于编程式导航
router.push(...)router.push方法会向history栈中添加一个新的记录,所以在浏览器中点击回退会回到之前的URL
router.replace(...)不会向history添加新纪录,而是替换掉当前的history记录 router.go(n) n是一个整数,代表在history记录中前进(+)或者后退(-)多少步
2.router与routes
app.use(router)会触发第一次导航且可以在任意组件以this.router与直接通过createRouter创建的router完全相同
this.$route可访问当前路由
3.query和parmas传参的区别
①query用path编写传参地址,params用name编写传参地址
②query刷新页面时参数不消失,params刷新页面时参数会消失
③query传参会显示在地址栏中,params传参不会显示在地址栏中
示例
this.$router.push({path:'/user',query:{id:'111'}})//相当于 this.$router.push({path:`/user/${id}`}) this.$router.push({name:'/user',params:{id:'111'}})
4.静态路由与动态路由的区别
静态路由:在路由对象中写死的资源,固定路由的路径在routes数组中
动态路由:适用于把某种模式匹配到的所有路由都映射到同一个组件;通过router.addRouter()方法添加;动态路径 参数以冒号开头
示例
const User={ template:'<div>User组件</div>' } const router=new VueRouter({ routes=[{ path:'user/:id', component:User }] })以上代码块/user/1与/user/2都会映射到相同的路由; 路径参数使用:标记,当匹配到一个路由时,参数值会被设置到this.$route.params中
5.嵌套路由
示例
const router=new VueRouter({ routes:[ { path:/school/:id, component:School, children:[ { path:'grade', component:Grade } ] } ] })注意: 以/开头的嵌套路径被当作根路径
6.命名路由
示例
const routes=[ { path:'/school/:id', name:'school', component:School } ] <router-link :to="{name:'school',params:{id:1}}">school</router-link> router.push({name:'school',parmas:{id:1}})