V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ghostheaven
V2EX  ›  Vue.js

监听 Vue Router 的变化

  •  
  •   ghostheaven · 2019-04-26 21:05:51 +08:00 via Android · 3125 次点击
    这是一个创建于 1798 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 beforeUpdate 还是 watch $route,这两种方式是不是等价的?

    5 条回复    2019-04-30 09:14:40 +08:00
    ss098
        1
    ss098  
       2019-04-26 21:23:50 +08:00
    watch $route 才是用来监听变化的吧,beforeUpdate 其他情况也会触发。
    ss098
        2
    ss098  
       2019-04-26 21:23:50 +08:00
    watch $route 才是用来监听变化的吧,beforeUpdate 其他情况也会触发。
    ghostheaven
        3
    ghostheaven  
    OP
       2019-04-26 21:26:30 +08:00 via Android
    @ss098 哪些情况?
    ss098
        4
    ss098  
       2019-04-26 21:58:50 +08:00
    yiranHZT
        5
    yiranHZT  
       2019-04-26 23:01:07 +08:00
    应该使用 Vue Router 的导航守卫吧。
    https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards

    例如,在 Electron 中不能直接看到 chrome 的当前 URL,所以我就用 Vue Router 的 `router.afterEach` 每次路由变化后在 console 打印当前路由信息,以验证路由没错误。
    ghostheaven
        6
    ghostheaven  
    OP
       2019-04-30 09:14:40 +08:00 via Android
    @yiranHZT @ss098 在 so 上找到一个答案,说 2.2 之前只能用 watch $route,之后增加了 beforeRouteUpdate,可以达到相同的功能。一个区别是 beforeRouteUpdate 只能在声明它的组件上有效(我理解应该是说只能在 router view 上),在子组件上不会被调用,而 watch 可以。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1067 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 22:43 · PVG 06:43 · LAX 15:43 · JFK 18:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.