vue-router使用
组件切换实现页面切换效果,需要借助vue-router来实现
1、简单使用
页面跳转,写一个页面组件
在router--->index.js---routes数组中加入一个路由即可
2、组件中实现页面跳转
两种方式
方式一:使用 router-link 标签,to 地址
<router-link to="/about"><button>点我调到about-->标签的跳转</button></router-link to="/about">
方式二:js控制
this.$router.push('/about')
能直接使用router的原因:router的index中导出router
main.js引入
路由跳转时,可以使用对象
1、通过对象跳转路由name形式: <router-link :to="{name:'about'}">
2 、通过对象跳转路由path形式: <router-link :to="{path:'/about'}">
3、 对象中可以有query属性,是个对象类型,会把里面的key-value拼到路径后面
4、在另一个页面中取出地址栏中数据:console.log(this.$route.query)
5、这种传递方式和 3 一样 <router-link to="/about?name=lqz&age=19">
6、注意区分(route和router):
this.$route:当前路由对象,当前路径,取传递数据
this.$router:整个路由对象,主要做跳转用
7、路径中分割参数
配置:
{
path: '/detail/:pk',
name: 'detail',
component: DetailView
},
在路由中取:
this.$route.params.pk
8、 路由跳转时,使用 7 的样子
-this.$router.push({name: 'detail', params: {pk: 999}})
-<router-link :to="{name:'detail',params:{pk:88}}">
this.router 的一些方法
this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
this.$router.back(): 请求(返回)上一个记录路由
this.$router.go(-1): 请求(返回)上一个记录路由
this.$router.go(1): 请求下一个记录路由
页面跳转携带数据
方式一:地址中携带 ? 后带 跳转的时候: -标签跳转: <router-link to="/userinfo?user_id=9"> <router-link :to="{name:userinfo,query:{user_id:88}}"> -js跳转 this.$router.push("/userinfo?user_id=9") this.$router.push({name:userinfo,query:{user_id:88}}) 取值的时候: this.$route.query.user_id # 方法二:/xx/:id/:name 配置路由: { path: '/userinfo/:id/:name', name: 'userinfo', component: UserDetail }, 跳转的时候: -标签跳转: <router-link to="/userinfo/88/lqz"> <router-link :to="{name:userinfo,params:{id:88,name:lqz}}"> -js跳转 this.$router.push("/userinfo/88/lqz") this.$router.push({name:userinfo,params:{id:88,name:lqz}}) 取值的时候: this.$route.params.id
多级路由