路由传参,[object Object]的情况,在接收的地方用JSON.parse()报错:Unexpected token o in JSON at position 1

一、问题描述

点击表格的 维护表 操作,实现新窗口跳转,并带一个参数(类型是对象),
在这里插入图片描述

1. 原页面的函数:

    MaintainOperate(row) {
    
    
      console.log("传的row:", row);
      let link = this.$router.resolve({
    
    
        path: "/table-matain",
        query: {
    
    
          currTableItem: row
        }
      });
      window.open(link.href, "_blank");
    }

在这里插入图片描述

2. 目标页面(路由为table-matain的页面):

  mounted() {
    
    
     console.log("接收方:", this.$route.query.currTableItem); // 打印结果为见图 [object,object]
  }

在这里插入图片描述

3. 更改了目标页面的代码(路由为table-matain的页面):

  mounted() {
    
    
     console.log("接收方:", JSON.parse(this.$route.query.currTableItem)); // 加了JSON.parse导致报错
  }

报错:Error in mounted hook: "SyntaxError: Unexpected token o in JSON at position 1"

二、解决办法

在query传参的时候,序列化一下那个对象,在接收参数的时候,再用JSON.parse()转一下即可

1. 原页面的函数:

  MaintainOperate(row) {
    
    
      let link = this.$router.resolve({
    
    
        path: "/table-matain",
        query: {
    
    
          currTableItem: JSON.stringify(row) // 序列化传递过去的对象
        }
      });
      window.open(link.href, "_blank");
    }

2. 目标页面(路由为table-matain的页面):

  mounted() {
    
    
     console.log("接收方:", JSON.parse(this.$route.query.currTableItem)); // 用JSON.parse转一下
  }

成功:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ddx2019/article/details/107759508