vue 跳转新页面并传参

前言

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

思路

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

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

    • ({ 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

Guess you like

Origin blog.csdn.net/qq_39763472/article/details/118599553