ghostheaven
V2EX  ›  Vue.js

监听 Vue Router 的变化

  •  
  •   ghostheaven · Apr 26, 2019 via Android · 4455 views
    This topic created in 2748 days ago, the information mentioned may be changed or developed.

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

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

    例如,在 Electron 中不能直接看到 chrome 的当前 URL,所以我就用 Vue Router 的 `router.afterEach` 每次路由变化后在 console 打印当前路由信息,以验证路由没错误。
    ghostheaven
    ghostheaven
    OP
    Apr 30, 2019 via Android
    6
    @yiranHZT @ss098 在 so 上找到一个答案,说 2.2 之前只能用 watch $route,之后增加了 beforeRouteUpdate,可以达到相同的功能。一个区别是 beforeRouteUpdate 只能在声明它的组件上有效(我理解应该是说只能在 router view 上),在子组件上不会被调用,而 watch 可以。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3152 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 80ms · UTC 04:32 · PVG 12:32 · LAX 20:32 · JFK 23:32
    ♥ Do have faith in what you're doing.