在页面中可以通过以下方式使用路由
1:通过router-link标签的方式
<router-link to="home">Home</router-link>
2:通过router的push的方式
this.$router.push({path: ‘/manage’});
在执行点击按钮跳转页面之前还会执行一系列方法,这时可以使用 this.$router.push(location) 来修改 url,完成跳转。
push 后面可以是对象,也可以是字符串:
// 字符串
this.$router.push('/home/first')
// 对象
this.$router.push({ path: '/home/first' })
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})
通过代码跳转案例
<template>
<div>
<button @click='userClick'>用户</button>
<button @click='profileClick'>档案</button>
</div>
</template>
<script>
export default{
data(){
return {
userId:'wushen'
}
},
methods:{
userClick(){
this.$route.push('/user/'+this.userId)
},
profileClick(){
this.$route.push({
path: '/profile',
query: {
name: 'wushen',
age:18,
height:1.88
}
})
}
}
}
</script>
跳转页面并传递参数的方法:
1.Params
-
name和params搭配刷新参数会消失this.$router.push({name:"",params:{id:""}})
-
path和query搭配,刷新页面参数不会消失,query中参数成了url中的一部分this.$router.push({path:"",query:{id:""}})
由于动态路由也是传递params的,所以在 this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面。
及通过路由配置的name属性访问
两种方式的区别是query传参的参数会带在url后边展示在地址栏,params传参的参数不会展示到地址栏。
在路由配置文件中定义参数:
/* router.js 文件*/
import Vue from "vue";
import Router from "vue-router";
import MediaSecond from "@/views/EnterprisePage/MediaMatrix/second"; //资讯列表
Vue.use(Router);
export default new Router({
routes: [ /* 进行路由配置 */
{
name: "MediaSecond",
path: "/MediaSecond",
component: MediaSecond
},
]
})
/* 后面还需要接一空行,否则无法通过 ESlint 语法验证 */
通过name获取页面,传递params:
this.$router.push({ name: 'MediaSecond',params:{artistName:artistName,imgUrl:imgUrl,type:2} })
在目标页面通过this.$route.params获取参数:
if (this.$route.params.type == 2) {
this.type = apis.getAtistDetails;
} else {
this.type = apis.getMessageList;
}
2.Query
页面通过path/name和query传递参数,该实例中row为某行表格数据
this.$router.push({ name: 'DetailManagement', query: { auditID: row.id, type: '2' } });
this.$router.push({ path: '/DetailManagement', query: { auditID: row.id, type: '2' } });
在目标页面通过this.$route.query获取参数:
this.$route.query.type
1.需要注意的是接收参数的时候是route而不是router。两种方式一一对应,名字不能混用。
2.由于动态路由也是传递params的,所以在 this.$router.push() 方法中path不能和params一起使用,否则params将无效。只能用name来指定页面。
3.不带参数,直接跳转页面
this.$router.push('/orderList')
this.$router.push({name:'orderList'})
this.$router.push({path:'/orderList'})
用query传参对象时需注意的地方
在vue项目中,我们用函数式编程this.$router.push跳转,用query传递一个对象时要把这个对象先转化为字符串,然后在接收的时候要转化为对象,要不然会接收不到参数。要不就把参数分开传递,不要放到对象里。
this.$router.push({
path: '/liveing',
query: {
routeParams: JSON.stringify({ liveUrl: url, flag: 2 })
}
});
接收:
let routeParams = JSON.parse(this.$route.query.routeParams)
this.currMeetingUrl = routeParams.liveUrl;
this.obcject = routeParams.flag;
第二种方法:不要套在对象里直接传递
this.$router.push({
path: '/liveing',
query: {
liveUrl: url,
flag: 2
}
});
接收:
let liveUrl = this.$route.query.liveUrl;
let flag = this.$route.query.flag;