首页 > 解决方案 > force component to rebuild on route change or vuex state change

问题描述

I want to get into VueJs / Vuex and created a small todo app. There are three links for "all todos", "pending ones" and "completed ones". It's the same route but with a different filter query.

When changing the route the component will not update, because it seems that updated query is not forcing an component update. But the computed event gets triggered.

I created a small example showing my current problem

https://codesandbox.io/s/6zx2p0m20r

If you click around on the todo links there will be no component update. If you head over to "another route" and head back, the component was updated (because of a completely different route).

How can I force to update the component on a query update within the same base route?

标签: vue.jsvuexvue-router

解决方案


You can add the beforeRouteUpdate navigation guard to reinitialize your data:

beforeRouteUpdate is 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.

(source)


beforeRouteUpdate(to, from, next) {
  this.currentTodoFilter = to.query.filter
  next()
}

You can also remove your updateTodoFilter method this way.


推荐阅读