路由模式
hash模式和history模式
hash模式
hash模式:在浏览器中符号’#’,以及’#'后面的字符称为hash
特点
1. hash 不会被包括在 http 请求中,对服务器端完全无用,因此,改变 hash 不会重新加载页面。
2. 可以为 hash 的改变添加监听事件:window.addEventListener("hashchange",funcRef,false)
3. 每一次改变 hash(window.localtion.hash),都会在浏览器访问历史中增加一个记录。
history模式
history模式:利用了 HTML5 History api 在浏览器中没有’#’,有浏览器兼容问题
特点
提供了两个新方法:
pushState(), replaceState()可以对浏览器历史记录栈进行修改,
以及popState事件的监听到状态变更
路由的跳转方式
第一种跳转方式:编程式导航
this.$router.push({ name: 'xxx',params: { id:xxx }})
this.$router.push({ path: '/xxx',query: { id:xxx }})
const userId = '123';
this.$router.push({ name: 'user', params: { userId }}) // -> /user/123
this.$router.push({ path: `/user/${userId}` }) // -> /user/123
第二种跳转方式:声明式
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
使用router-link标签套在要点击的内容外面,to指定跳转的路径
三者区别
this.$router.push
跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面
this.$router.replace
跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)
this.$router.go(n)
向前或者向后跳转n个页面,n可为正整数或负整数
路由传参
例如有一个场景: 点击列表跳转到对应的详情页,携带id,便于详情页获取数据
第一种传参:
query 传参:
goDetail(id) {
this.$router.push({path:'/detail',query:{id:id}})
}
到了跳转到的页面 接收:
this.$route.query.id
第二种传参
params传参
goDetail(id) {
this.$router.push({name:'detail',params:{id:id}})
}
到了跳转到的页面 接收:
this.$route.params.id
第三种传参
动态路由传参:
goDetail(id) {
this.$router.push({path:`/detail/${id}`})
}
需要对应路由配置:
{
path:'/detail/:id',
name:'detail',
}
到了跳转到的页面 接收:
this.$route.params.id
区别
- query传参的参数会带url后面展示在地址栏,params传参的参数不会展示;
- query传参配置的是path或name,params传参配置的是name;
- params传参刷新后会无效,query会保存传递过来的值,刷新不变;
- params可以和动态路由一起使用,query不可以
router 和 route 区别
router为路由实例,$route为当前router跳转对象,里面可以获取name,path,query,params
路由的嵌套
子路由 又叫嵌套路由。
除了app.vue 是必须的自带之外我们也可以自己写一个坑用来展示页面
是谁的子路由 就会在谁的坑里展示 默认的最外层是app的子路由
const routes = [
{
path: "/index",
name: "index",
component: () => import("../views/Index.vue"),
children: [
{
path: "/shopcar",
name: "shopcar",
component: () => import("../views/Shopcar.vue"),
},
],
},
];
vue路由的基础用法
1 .安装
npm install vue-router --save
2 .main.js中
//Vue路由:引入
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//Vue路由:引入并创建组件
import BYHome from './components/BYHome.vue'
import BYNews from './components/BYNews.vue'
import HelloWorld from './components/HelloWorld.vue'
//Vue路由:配置路由
const routes = [
{path: '/home', component: BYHome},
{path: '/news', component: BYNews},
{path: '/helloworld', component: HelloWorld},
{path: '*', redirect: '/home'} /*默认跳转路由 */
]
//Vue路由:实例化VueRouter
const router = new VueRouter({
routes //缩写,相当于 routes:routes
})
new Vue({
router, //Vue路由:挂载路由
render: h => h(App),
}).$mount('#app')
//Vue路由:根组件的模板里面放上下面这句话,需要在App.vue 中配置路由出口:路由匹配到的组件将渲染在根组件App.vue中
<router-view></router-view>
//路由跳转
<router-link to="/home">首页</router-link>
<router-link to="/news">新闻</router-link>
<router-link to="/helloworld">helloWorld</router-link>