博客
关于我
Vue路由跳转如何传递一个对象过去?
阅读量:686 次
发布时间:2019-03-17

本文共 1018 字,大约阅读时间需要 3 分钟。

正确的数据传输方法

在开发过程中,当你需要将复杂的数据对象进行传输时,直接使用 JSON.stringify()JSON.parse() 并不会奏效,因为解析时会报错。以下是解决问题的详细步骤:

  • 字符串编码和解码:在传输过程中,使用 encodeURIComponent()JSON.stringify() 转换后的字符串进行编码,确保数据不会被破坏。例如:

    const data = { id: 123, name: "Example Data" };const jsonData = JSON.stringify(data);const encodedData = encodeURIComponent(jsonData);

    URL 中如 encodeURIComponent 的作用是替换不安全字符,如空格变成 %20,这确保数据不会改变。

  • URL 解码:接收端通过使用 decodeURIComponent() 来解码 URL 参数,再将其解析为 JSON 对象。例如:

    const dataFromUrl = decodeURIComponent(window.location.search);const parsedData = JSON.parse(dataFromUrl);

    这样可以恢复原始的 JSON 数据。

  • 转换步骤示例:

    • 发送端
      const data = { id: 123, name: "Test Data" };const jsonString = JSON.stringify(data);const encoded = encodeURIComponent(jsonstring);this.$router.push(`/details/${encoded}`);
    • 接收端
      const urlParams = new URL(window.location.search);const data = JSON.parse(decodeURIComponent(urlParams.obj));
  • 验证步骤:

    • 查看 Network 调试器:确保传输的数据与期望的 JSON 格式一致。
    • 控制台日志:检查解解析的数据结构是否正确,确认是否为预期对象。
  • 通过以上方法,可以确保数据传输过程中的正确性,避免由于字符转换导致的错误。这样既能解决 JSON 解析问题,也保证了数据的完整性和可读性。

    转载地址:http://dkthz.baihongyu.com/

    你可能感兴趣的文章
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>