0

I'm trying to restart my component when the route changes:

  beforeRouteUpdate (to, from, next) {
    Object.assign(this.$data, this.$options.data())
      console.log(to.query);
      next();
    } 

but it doesn't work; it only prints the console.log. I've also tried this.$options.data.call(this) and apply.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
Albert Jovinskyi
  • 349
  • 1
  • 3
  • 13
  • Have a look at this post, this solution should work for you: https://stackoverflow.com/questions/35604987/is-there-a-proper-way-of-resetting-a-components-initial-data-in-vuejs – wwerner Oct 18 '18 at 16:53

2 Answers2

2

In order to force Vue to re-render same component upon route query change, it is possible to assign a key to the <router-view it mount's into and push router to the page with the same route name or path.

Example:

Mounting point:

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

Component navigation, assuming route name is blog

<router-link :to={ name: 'blog', query: { count: 10 } }>Link to the same route</router-link>

This is assuming that you want to reset data of page component while navigating to the same page component with different data.

If component that you want to reset is not the route component, it is possible to reset it's data with watch option, while saving original data.

Example:

data () {
  return {
    initialData: {
      //  some initial data
    },
    data: {}
  }
},
watch: {
  '$route.fullPath': {
    immediate: true, // Immediate option to call watch handler on first mount
    handler () {
      this.resetData()
    }
  }
},
methods: {
  resetData () {
    this.data = Object.assign({}, this.initialData)
  },
},

Note, that any $route options can be watched and additional conditions added to handler via next and previous arguments.

aBiscuit
  • 4,414
  • 1
  • 17
  • 28
0

Try this.$router.reload()