编程式导航
注意:在 Vue 实例内部,你可以通过 router.push
- 声明式导航
<router-link></router-link>
- 声明式导航
- 编程式导航
js 路由对象提供的 方法来 跳转,路由实例调用方法(router 路由 给Vue灌入一个对象,就是 路由对象(new VueRouter())
- 编程式导航
**使用$router.push()方法**
1. 参数为字符串
this.$router.push('跳转路由的path')
2. 参数为对象
this.$router.push({
path:'/home'
})
this.$router.push({
name:'home' //命名路由
})
编程式导航路由传参汇总
- 动态路由传参
{
// 动态路径参数 以冒号开头
path:'/news/:id',
component: NewsSon
},
- query传参 (最好搭配path)
this.$router.push({
//query传参 path一起使用 (最好不要和name一起使用)
/*
优点:
页面刷新 参数不丢失
缺点:
参数 放在url上 显式的
获取:
this.$route.query.a
this.$route.query.b
*/
path:'/home',
query:{
a:10,
b:20
}
})
- params传参(搭配name命名路由)
this.$router.push({
//params传参 (和name是固定搭配)
/*
优点:
隐式 (地址上不显示)
缺点:
刷新丢失
注意:
params 传参和命名固定搭配
获取
this.$route.params.a
*/
name:'news',
params:{
a:10,
b:30
}
})
编程式导航 go
this.$router.go(n)
n
0 刷新
-1 回退
1 前进一步
路由模式
路由模式
hash路由 默认的
window.addEventListener("hashchange",(e)=>{
// 根据hashchange 事件 来动态切换 不同组件
})
history
路由好处:不再有#存在
原理:
history对象有一个 pushState
注意:
此模式 需要 服务器 做配置
/
服务配置:
如果 你的地址 / 重定向到 当前 index.html(有vue,vueRouter)下