目录
Vue2:
1. 路由:
2. 路由规则:
3. 实现切换(active-class可配置高亮样式)
4. 指定展示位置
5. 路由的query参数
6. params传参:
7. 多级路由
8. 路由的props配置
9. 的replace属性
10. 编程式路由导航
11. 缓存路由组件
12. 两个新的生命周期钩子
Vue3:
编写router配置项(在router文件夹中的index.js文件中)
//引入VueRouter插件import VueRouter from 'vue-router'//引入路由组件import About from '../components/Aboutimport Home from '../componets/Home//创建router实例对象,去管理路由规则const router = new VueRouter({routes:[{path:'/about',component:About},{path:'/home',component:Home}]})//暴露routerexport default router
About
1)传递参数的组件(携带参数有【to的字符串】写法和【to的对象】写法):
//跳转并携带query参数,to的字符串写法{{m.title}} //跳转并携带query参数,to的对象写法{{m.title}}
2)接收参数的组件:
- 消息编号:{{$route.query.id}}
- 消息标题:{{$route.query.title}}
首先我们要注意的第一个点:
1)传递参数的组件:
{{m.title}} {{m.title}}
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!!
2)接收参数的组件:
- 消息编号:{{$route.params.id}}
- 消息标题:{{$route.params.title}}
配置路由规则(在router文件中的index.js文件中)使用children配置项:
routes:[{path:'/about',component:About,},{path:'/home',component:Home,children:[//通过children配置子级路由{path:'news', //此处一定不要写成 /newscomponent:News,},{path:'message',//同理可得component:Message,}]}]
ps:children配置项里的path路径不要加【/】
作用:让路由组件更方便的收到参数。
{path:'message',component:Message,children:[{name:'xiangqing',path:'detail',component:Detail, //props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件//props:{a:1,b:'hello'}//props的第二种写法,值为布尔值.若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件//props:true//props的第三种写法,值为函数(在query接收参数时)props($route){return {id:$route.query.id,title:$route.query.title}}}]}
几个注意点:
- 路由组件通常存放在pages文件夹中,一般组件通常存放在components文件
- 通过切换,‘隐藏’了的路由组件,默认是被销毁掉的,需要的时候再去挂载
- 每个组件都有自己的$route属性,里面存储自己的路由信息
- 整个应用只有一个router,可以通过组件的$router属性获取到
除了借助
结构:
- {{m.title}}
Click触发的事件:
methods:{pushShow(m){this.$router.push({name:'xiangqing',query:{id:m.id,title:m.title}})},replaceShow(m){this.$router.replace({name:'xiangqing',query:{id:m.id,title:m.title}})}}}
- this.$router.forward() 前进
- this.$router.back() 后退
- this.$router.go(-2) 正数是前进几步,负数是后退几步
作用:让不展示的路由组件保持挂载,不被销毁
注意:News是组件名
1)activated 路由组件被激活时触发
2)deactivated 路由组件失活时触发。
activated(){//激活console.log('激活了')this.timer = setInterval(() =>{this.opacity -= 0.01if(this.opacity <= 0)this.opacity = 1},16)},deactivated(){//失活console.log('失活了')clearInterval(this.timer)}
Vue2的路由基本介绍完了,那么在Vue3中,又作出了哪些调整呢?
在index.js中:
在main.js中:
VUE3中某些组件使用: