Update VueJs component when changing route

Is there a way to override a component when changing a route? I am using Vue Router 2.3.0 and I am using the same component on multiple routes. It works fine the first time, or if I go to a route that does not use the component, then go to what it does. I convey what is different in the details.

{
  name: 'MainMap',
  path: '/',
  props: {
    dataFile: 'all_resv.csv',
    mapFile: 'contig_us.geo.json',
    mapType: 'us'
  },
  folder: true,
  component: Map
},
{
  name: 'Arizona',
  path: '/arizona',
  props: {
    dataFile: 'az.csv',
    mapFile: 'az.counties.json',
    mapType: 'state'
  },
  folder: true,
  component: Map
}

Then I use the details to load a new map and new data, but the map remains the same as when I first loaded. I'm not sure what is going on.

The component is as follows:

data() {
  return {
    loading: true,
    load: ''
  }
},

props: ['dataFile', 'mapFile', 'mapType'],

watch: {
    load: function() {
        this.mounted();
    }
},

mounted() {
  let _this = this;
  let svg = d3.select(this.$el);

  d3.queue()
    .defer(d3.json, `static/data/maps/${this.mapFile}`)
    .defer(d3.csv, `static/data/stations/${this.dataFile}`)
    .await(function(error, map, stations) {
    // Build Map here
  });
}
+12
source share
3 answers

.

-, mounted() . , mounted , mounted -, Vue , , , , , mounted . beforeUpdate updated beforeUpdate.

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

, d3, , mounted updated . , , mounted .

+9

: key <router-view> :

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

, Vue Router . , - , ( , Map).

+28

,

$route.
, to from.

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

--- 3 2019

, , , , vue-router, In Component Guards. ( ). .

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

, next(). , ! !

+2
source

Source: https://habr.com/ru/post/1675008/


All Articles