vue-router
路由
根据浏览器地址栏上的url,去切换组件(RouterView)
两种模式
hash模式 # 底层原理 监控hash值变化切换组件 onhashchange
history模式 history pushState 切换组件
router和route区别
router vue-router插件用createRouter 方法创建出里路由的实例对象
route 这是路由表里的路由对象
route对象
name 命名路由
path 路由匹配的路径
component 路由匹配到路径的时候,渲染的组件
alias 路径的别名
redirect:
{
path:"/",
// redirect:"/home" //路由的重定向
redirect:{name:'home'}
}
404页面处理
{
path:"/:pathMatch(.*)",
component:NotFound
}
路由的元数据(meta)
路由对象里放置变量的地方
{
path:"/:pathMatch(.*)",
component:NotFound,
meta:{ //路由对象的元数据
flag:true //flag true 导航条隐藏 false 导航条可见
}
}
监控路由对象的变化
watch:{
$route(n){ //监听当前路由对象的变化 n 就是最新的路由对象
console.log(n.meta.flag)
}
}
嵌套路由
{
path:"/three", //分类的路由对象
component:Three,
children:[ //子路由
{
path:"phone", // /three/phone 才能匹配
component:Phone
},
{
path:'cloth',
component:Cloth
},
{
path:'edutool',
component:EduTool
}
]
},
动态路由
路由的path上含有变量,这样路由叫动态路由
{
path:"/detail/:id", //动态路由
component:Detail
}
<RouterLink :to="'/detail/'+item.id">详情</RouterLink>
拿到动态路由参数 this.$route.params.id
路由传值
query / params
编程式导航
this.$router
go
back
forward
replace 不能返回到上一级
push