Update VueJs component on route change Update VueJs component on route change vue.js vue.js

Update VueJs component on route change


You may want to add a :key attribute to <router-view> like so:

<router-view :key="$route.fullPath"></router-view>

This way, Vue Router will reload the component once the path changes. Without the key, it won’t even notice that something has changed because the same component is being used (in your case, the Map component).


UPDATE --- 3 July, 2019

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!


Below is my older answer.
Only saved for the purpose of "progress"

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)  }},


The alternate solution to this question handles this situation in more cases.

First, you shouldn't really call mounted() yourself. Abstract the things you are doing in mounted into a method that you can call from mounted. Second, Vue will try to re-use components when it can, so your main issue is likely that mounted is only ever fired once. Instead, you might try using the updated or beforeUpdate lifecycle event.

const Map = {  data() {    return {      loading: true,      load: ''    }  },  props: ['dataFile', 'mapFile', 'mapType'],  methods:{    drawMap(){        console.log("do a bunch a d3 stuff")    }  },  updated(){    console.log('updated')    this.drawMap()  },  mounted() {    console.log('mounted')    this.drawMap()  }}

Here's a little example, not drawing the d3 stuff, but showing how mounted and updated are fired when you swap routes. Pop open the console, and you will see mounted is only ever fired once.