vue 跳转新页面并传参

前言

  最近开发过程中有个新的需求,需要点击事件后跳转新的页面然后通过传参的数据展示表格。
  具体来说,在一个Modal容器中,有一行字 “XXX目录”,点击这个目录,就会跳转新的页面,将需要的参数传给新页面的组件,然后向后端获取数据并且展示表格。
  因为是在项目中,我们肯定要使用路由的方式。

思路

  • 首先查了一下有两种方式打开新页面

    • this.$router.push()
    • this.$router.resolve()
      这两种方式的区别就是,push是在当前页面打开新的路由并加载组件,resolve是直接打开新的标签页并加载组件。
  • 使用方式

    	this.$router.push() // 在当前页面打开location
    	let newPage = this.$router.resolve() window.open(newPage.href, '_blank')
    
  • 然后关于传参也有两种方式

    • ({ path: ‘’, query: {} })
    • ({ name: ‘’, params: {} })
      要注意的是,官方文档明确写出:
      在这里插入图片描述
        所以,一定是 name 搭配params,或者 path,如果用path,需要传参,就需要path + query。
        而query和params又有区别,在当前的需求中,需要的是打开新页面,并拿到参数,而params打开新的标签页后,地址栏的url中不会附带参数,所以通过 this.$route.params拿不到。所以只能用query。
        也即,this.$router.push 方法,添加路由转到新组件,可以用 params 和 query;
        而 this.$router.resolve 方法,打开新的标签页,只能用query,否则拿不到参数。

项目具体代码

  1. router.config.js
{
    path: '/obeyRuleScreening/obeyRuleScreening/policyContent',
    name: 'policyContent',
    component: () => import('@views/obeyRuleScreening/policyContent'),
    props: true
  }
  1. 点击事件
<a-button type="primary" @click="open(item.yiju, item.drugList)">{{item.yiju}}</a-button>

open(catalog, highlight) {
   let formData = {};
   formData.province = this.province;
   let highlightItem = [];        
   for(let item in highlight) {
     highlightItem.push(highlight[item].yaopin);
   }
   formData.highlight = highlightItem;
   formData.catalog = catalog;
   formData.pageNo = this.resultArg.current;

   // console.log('formData = ', formData);

   let newPage = this.$router.resolve({ 
       path: '/obeyRuleScreening/obeyRuleScreening/policyContent', 
       query: formData
     });

   window.open(newPage.href, '_blank');
}, 

  1. 新页面获取参数
created() {
    this.fetchData(1);
  },
methods: {
 fetchData(pageNo) {
   const formData = this.$route.query;

   formData.pageNo = pageNo;

   postAction('your interface', formData)
     .then(res => {
       if(res.success) {
         
       }
     });
 },
}

router 和 route的区别

  1. $router : 是路由操作对象,只写对象; 通过 router来添加路由等
  2. $route : 路由信息对象,只读对象;通过route来读取参数 this.$route.params or this.$route.query
  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值