目录
一、路由
- 路由就是路径和组件的映射关系。
- 在一个页面里, 切换业务场景
- 单页面 SPA(single page web application) 应用
- 整个应用只有一个完整的页面
- 点击页面中的导航链接不会刷新页面 ,只会做页面的局部更新
- 数据需要通过ajax请求获取
二、路由的基本适使用
安装vue-router,命令 npm i vue-router
应用插件:Vue.use(VueRouter)
编写router配置项
指定展示位置
三、几个注意点
- 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹
- 通过切换,隐藏了的路由组件,默认是被销毁掉的,需要的时候在挂载
- 每个组件都有自己的$route属性,里面存储着自己的路由信息
- 整个应用只有router,可以通过组件的**$router**属性获取到
四、多级路由
routes:[ { path:'/about', component:About }, { path:'/home', component:Home, // 二级路由 children:[ { //这里不用加斜 path:'news', component:News, }, { //这里不用加斜 path:'message', component:Message, } ] } ]
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
五、路由的query参数
1、传递参数
<li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数 to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数 to的对象写法 --> <router-link :to="{ //你要去到哪个组件 path:'/home/message/detail' , query:{ id:m.id, title:m.title } }"> {{m.title}} </router-link> </li>
2、接收参数
$route.query.id $route.query.title
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
六、编程式路由跳转 $router
- 前进 forward() go(1)
- 后退 go(-1) back()
- 切换路由 push("/about")
- 替换路由 replace("/about")
七、 路由信息 $route
- 路由参数 params
- 查询 query
- 地址 path
- 全地址 fullPath
- 名称 name
- 哈希值 hash
八、路由守卫
全局前置
全局后置
// 后置路由守卫 router.afterEach((to,from) =>{ console.log(to,from) })
独享路由守卫
{ //这里不用加斜 name:'xinwen', path:'news', component:News, meta:{isAuth:true}, // 独享路由守卫 beforeEnter:(to,from,next)=>{ if(to.meta.isAuth){ if(localStorage.getItem('school')=== 'aiguigu'){ next() }else{ alert("请登录") } } } },
组件内守卫
// 组件路由 // 通过路由规则,进入该组件时被调用 beforeRouteEnter(to,from,next){ console.log('我进来了',to) }, // 通过路由规则,离开该组件时被调用 beforeRouteLeave(to,from,next){ }
九、 路由元信息
{ path: '/user', //配置的路径 name: "user", //名称 meta: { noFooter: true, //在meta中自定义属性noFooter true requireAuth:true }, component: () => import('../views/user/UserView.vue') //对应的组件 },
十、路由查询参数
传递 next("/login?redirect=/cart")
获取 var redirect = this.$route.query.redirect| | '/user'