在路由更改时更新 VueJs 组件 [英] Update VueJs component on route change

查看:27
本文介绍了在路由更改时更新 VueJs 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在路由更改时重新渲染组件?我正在使用 Vue Router 2.3.0,并且在多个路由中使用相同的组件.第一次运行正常,或者如果我导航到不使用该组件的路由,然后转到使用该组件的路由.我正在传递道具的不同之处

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 if I navigate to a route that doesn't use the component and then go to one that does. I'm passing what's different in props like so

{
  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'm using the props to load a new map and new data, but the map stays the same as when it first loaded. I'm not sure what's going on.

组件如下所示:

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

推荐答案

这个问题的替代解决方案可以在更多情况下处理这种情况.

首先,您不应该自己调用 mounted().将您在 mounted 中所做的事情抽象为一个可以从 mounted 调用的方法.其次,Vue 会尽可能重用组件,因此您的主要问题可能是 mounted 只被触发一次.相反,您可以尝试使用 updatedbeforeUpdate 生命周期 事件.

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

这是一个小例子,不是画d3的东西,而是展示如何安装updated 在您交换路由时被触发.弹出控制台,你会看到 mounted 只被触发一次.

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.

这篇关于在路由更改时更新 VueJs 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆