vue中this.$router.push()路由传值和获取的两种常见方法

811 阅读1分钟

页面跳转可以使用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 }})

跳转页面并传递参数的方法(两种):params和query

1.params

this.$router.push()方法中path和params不能一起使用,否则params无效。需要用name来指定页面。即通过路由配置的name属性访问。

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/homework',
    name: 'Homework',
    component: () => import(/* webpackChunkName: "userpage" */ '../views/Homework.vue')
  },
  {
    path: '/homeworkModify',
    name: 'HomeworkModify',
    component: () => import(/* webpackChunkName: "userpage" */ '../views/HomeworkModify.vue')
  }
]

通过name获取页面,传递params:

this.$router.push({ 
  name: 'HomeworkModify',
  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/namequery传递参数,该实例中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

两者的区别是:使用 path + query,参数会显示在url上,而 name + params 参数不会显示在url上。