Vue Router Parameter Object Type Change On Browser Back Button

元气小坏坏 提交于 2021-02-05 11:46:52

问题


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]".

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


回答1:


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

...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)

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...

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

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...



来源:https://stackoverflow.com/questions/63844816/vue-router-parameter-object-type-change-on-browser-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!