浏览器返回按钮上的 Vue 路由器参数对象类型更改 [英] Vue Router Parameter Object Type Change On Browser Back Button

查看:45
本文介绍了浏览器返回按钮上的 Vue 路由器参数对象类型更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在传递一个参数论坛,它是一个对象到 Vue.js 中的路由(使用 vue-router)

I am passing a parameter forum, which is an Object to a route in Vue.js (using vue-router)

  {
    path: '/forum/:forum',
    name: 'ForumView',
    component: ForumView,
    props: true
  }

当我通过在页面上使用另一个链接(到诸如论坛/帖子之类的东西)离开该特定论坛路线,然后尝试使用浏览器中的后退按钮返回表单页面时,我在控制台

When i leave that specific forum route by using another link( to something like forum/post) on the page and after that try to go back to the form page using the back button in the browser I get the following error in the console

Invalid prop: type check failed for prop "forum". Expected Object, got String with value "[object Object]".

所以路由器在使用路由器链接的时候传递了javscript对象.但是当使用浏览器的后退按钮(访问历史)时,对象被转换为字符串.

So the router passes the javscript object when using the router link. But when using the back button of the browser (accessing the history), the object is converted into a string.

很好奇是否有解决方案,或者我不能/不应该将对象作为参数传递

Curious if there is a fix for that or if I can't / shouldn't pass objects as parameters

推荐答案

但是在使用浏览器的后退按钮(访问历史记录)时,对象被转换为字符串"

"But when using the back button of the browser (accessing the history), the object is converted into a string"

...这并不完全正确.该对象会更快地转换为字符串 - 准确地说,是在您导航到 forum 路线时.当您使用后退按钮时,根本没有任何对象.只有带有动态 :forum 段的 URL 被文本[object Object]"替换;(只需检查浏览器的 URL 栏)

...this is not entirely correct. The object is converted to a string much sooner - at the time you are navigating to your forum route to be precise. When you use back button, there is no object at all. There is only URL with dynamic :forum segment replaced by the text "[object Object]" (just check browser's URL bar)

这是通过路由器传递对象时的问题.因为即使你在历史模式下使用 Router 并且在后台使用浏览器的 history API,路由在调用 history.pushState<时不会存储任何参数/代码>.它只推送 URL.因此,如果您确实需要将某些内容传递给目标组件,则应将该信息以动态段或查询字符串的形式编码在 URL(路由定义)中...

This is the problem when passing objects through the router. Because even if you use Router in history mode and the browser's history API is used behind the scenes, router doesn't store any parameters when calling history.pushState. It pushes only URL. So if you really need something to pass to a target component, that information should by encoded in the URL (route definition) in the form of dynamic segment or as query string...

这种解决方案的另一个好处是,当用户复制/粘贴 URL 时,您的应用不会停止工作:)

Another benefit of such solution is that your app doesn't stop working when user copy/paste the URLs :)

或者你可以使用类似 Vuex 的东西来创建共享状态,并且只传递一些简单的标识符,这样更容易放入 url/route...

Or you can use something like Vuex to create shared state and only pass around some simple identifier which is much easier to put in the url/route...

这篇关于浏览器返回按钮上的 Vue 路由器参数对象类型更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆