router.currentRoute 显示的路由与 router.currentRoute.value 不同
我正在尝试获取组件的当前路由,但 router.currentRoute 显示出一些奇怪的行为。
router.currentRoute
显示预期路由 /admin
:
RefImpl {__v_isShallow: true, dep: undefined, __v_isRef: true, _rawValue: {…}, _value: {…}}
dep: Set(1) {ReactiveEffect}
__v_isRef: true
__v_isShallow: true
_rawValue: {fullPath: '/admin', path: '/admin', query: {…}, hash: '', name: 'login', …}
_value: {fullPath: '/admin', path: '/admin', query: {…}, hash: '', name: 'login', …}
value: Object
fullPath: "/admin"
hash: ""
href: "/admin"
matched: [{…}]
meta: {}
name: "login"
params: {}
path: "/admin"
query: {}
redirectedFrom: undefined
[[Prototype]]: Object
[[Prototype]]: Object
但 router.currentRoute.value
显示路由 /
:
{path: '/', name: undefined, params: {…}, query: {…}, hash: '', …}
fullPath: "/"
hash: ""
matched: []
meta: {}
name: undefined
params: {}
path: "/"
query: {}
redirectedFrom: undefined
[[Prototype]]: Object
因此我不能使用应显示当前路由的 router.currentRoute.value.path
。这种行为是预期的吗?如何获取组件当前的路径?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从格式来看,您似乎正在使用console.log(或类似)API 来观察代码效果。
请注意,几乎所有现代浏览器在控制台中显示的是对象的“惰性”视图(记录对象时)
检查 此示例(大致遵循 Vue Router 使用的数据结构)
结果: < 的每个日志code>router.currentRoute 显示完全相同的值(与
router.currentRoute.value
的日志相反)现在尝试相同的操作,但在每次单击后展开记录的对象...
TL:DR 不要相信console! - 您看到的值不一定是执行
console.log
时对象的值。要解决此问题,请使用
console.log(JSON.parse(JSON.stringify(obj)))
代替...Given by the formatting it seems you are using
console.log
(or similar) API to observe the code effects.Note that what almost all modern browsers shows in the console is the "lazy" view of the object (when logging objects)
Check this example (which roughly follows the data structures used by Vue Router)
Result: Each log of
router.currentRoute
shows exactly same value (opposed to logs ofrouter.currentRoute.value
)Now try the same thing but unfold the logged object after each click...
TL:DR Do not trust the console! - the value you see is not necessarily the value of the object at the time
console.log
was executed.To workaround the issue use
console.log(JSON.parse(JSON.stringify(obj)))
instead...