[Vuejs]-Is there a way to force a router-view component reload within the same route?

0👍

If you need to reload the view when this.pageKey changes, it is probably because you load the data in your created() or mounted() lifecycle handler. Your solution is a possibility, and probably the only real possibility if you require the transition to play on a change of this.pageKey.

Otherwise, consider moving your logic of loading data to a method, and load it in an immediately invoked watcher on this.pageKey. This means it loads on startup, and also loads when the pageKey has been changed.

computed: {
  // Vuex if you use it, or some other way of storing the pageKey
  ...mapGetters('pageKey')
},

watch: {
  pageKey: {
    immediate: true,
    handler () {
      this.loadData();
    }
  }
},

methods: {
  loadData() {
    // noop
  }
}

If you want to eliminate pageKey at all, one way to do it is by simply calling loadData in the click handler of the refresh button, or emitting an event. If the component containing the button and the component handling loading of data are not positioned nicely for a traditional event, you can always create an event bus and listen for it that way:

// main.js
Vue.prototype.$bus = new Vue();
// MyComponent.vue
created() {
  this.$bus.$on('force-refresh', this.loadData);
},

beforeDestroy() {
  // Prevent memory leaks
  this.$bus.$off('force-refresh', this.loadData);
},

methods: {
  loadData() {
    // noop
  }
}
// MyButton.vue
<template>
  <button @click="forceRefresh">I want all the new data</button>
</template>

<script>
export default {
  methods: {
    forceRefresh() {
      this.$bus.$emit('force-refresh');
    }
  }
}
</script>

Leave a comment