Update VueJs component on route change

后端 未结 3 1954
旧巷少年郎
旧巷少年郎 2020-12-25 13:34

Is there a way to re-render a component on route change? I\'m using Vue Router 2.3.0, and I\'m using the same component in multiple routes. It works fine the first time or i

3条回答
  •  不知归路
    2020-12-25 14:31

    This is old answer, latest answer is below

    My solution to this problem was to watch the $route property.
    Which will ended up you getting two values, that is to and from.

    watch: {
      '$route'(to, from) {
        const id = to.params.id
        this.AJAXRequest(id)
      }
    },
    

    UPDATE --- 3 July, 2019

    The principle is same as above, however turns out I found this thing on vue-router documentation, it's called In Component Guards. By the description of it, it really suits your needs (and mine actually). So the codes should be something like this.

    export default () {
      beforeRouteUpdate (to, from, next) {
        // called when the route that renders this component has changed,
        // but this component is reused in the new route.
        // For example, for a route with dynamic params `/foo/:id`, when we
        // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
        // will be reused, and this hook will be called when that happens.
        // has access to `this` component instance.
        
        const id = to.params.id
        this.AJAXRequest(id)
        next()
      },
    }
    

    As you can see, I just add a next() function. Hope this helps you! Good luck!

提交回复
热议问题