路由绑定不更新子组件

Route binding not updating sub component

我很难理解组件和路由是如何协同工作的。在文档中,他们只讨论了一个级别的组件。如果有多个级别,它看起来不像在工作。

这是我做的http://jsfiddle.net/uvqpracr/7/

,当你点击 init(1) 时,它用 1 初始化计数器,当你点击 init(5) 时,它用 初始化计数器]5。在路由组件中,我声明 v-bind:init-counter="$route.params.initCounter 所以当我在 counter-container 时,写 {{init-counter}} 是有效的,但是在子组件 counter 中,如果我写 v-bind:init-counter="initCounter" 事件它不起作用。

this documentation中,我可以阅读:

One thing to note when using routes with params is that when the user navigates from /user/foo to /user/bar, the same component instance will be reused. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. However, this also means that the lifecycle hooks of the component will not be called.

我想知道这是否是我尝试做的事情不起作用的原因。如果是这样,我真的很想知道我应该如何以简单的方式做到这一点。

首先,是的,组件(counter-container 及其子组件 counter)仅创建一次。

查看日志 demo JSFiddle。无论您点击链接多少次,created() 每次只调用一次(查看控制台)。

and when you click on init(1) it initialize the counter with 1 and when you click on init(5) it initialize the counter with 5

不完全是。我的意思是,点击并不总是初始化 counter 变量。

实际上,当您单击它们时,路线会发生变化,然后 initCounter(不是 counter,不是 total)会发生变化。

第一次点击,因为之前没有创建组件,那么initCounter的值会被用来初始化counter (和 total)。

但是在随后的点击中,即使 initCounter 确实改变了嵌套组件,它也不会影响 counter/total 变量,因为它们已经被创建。

勾选 demo JSFiddle。我添加了 counter: {{ counter }} / initCounter: {{ initCounter }} 的显示,因此您也会在 counter 组件中看到 initCounter 变化。


每次更新

所以,您现在知道 initCounter 将仅在首次创建组件时用于设置 counter/total 一次。

如果您想在 initCounter 发生变化时更新它们,解决方案是观察路线(使用 watch: { '$route' (to, from) { /* react here */ } }),或者更具体地说,观察 initCounter.

检查 this other demo JSFiddle。这个使用 watch 并在 initCounter 更新时更新 counter/total