使用 Vue Router 响应参数更改的最佳实践 [英] Best Practice for Reacting to Params Changes with Vue Router
问题描述
当使用带有像 /foo/:val
这样的路由的 Vue Router 时,你必须添加一个 watcher 到 对参数更改做出反应.这会导致在 URL 中有参数的所有视图中出现一些令人讨厌的重复代码.
When using Vue Router with routes like /foo/:val
you have to add a watcher to react for parameter changes. That results in somewhat annoying duplicate code in all views that have parameters in the URL.
这可能类似于以下示例:
This could look like the following example:
export default {
// [...]
created() {
doSomething.call(this);
},
watch: {
'$route' () {
doSomething.call(this);
}
},
}
function doSomething() {
// e.g. request API, assign view properties, ...
}
有没有其他方法可以克服这个问题?created
和 $route
更改的处理程序可以合并吗?是否可以禁用组件的重用,以便根本不需要观察者?我正在使用 Vue 2,但这对 Vue 1 也可能很有趣.
Is there any other way to overcome that? Can the handlers for created
and $route
changes be combined? Can the reuse of the component be disabled so that the watcher would not be necessary at all? I am using Vue 2, but this might be interesting for Vue 1, too.
推荐答案
我刚刚找到了一个可能的答案,感谢 GitHub 问题如下.
One possible answer that I just found thanks to a GitHub issue is the following.
可以使用 key
属性也用于 v-for
让 Vue 跟踪视图中的变化.为此,您必须将属性添加到 router-view
元素:
It is possible to use the key
attribute that is also used for v-for
to let Vue track changes in the view. For that to work, you have to add the attribute to the router-view
element:
<router-view :key="$route.fullPath"></router-view>
将它添加到视图后,您不再需要观看 $route
.相反,Vue.js 将创建一个全新的组件实例并调用 created
回调.
After you add this to the view, you do not need to watch the $route
anymore. Instead, Vue.js will create a completely new instance of the component and also call the created
callback.
然而,这是一个全有或全无的解决方案.它似乎在我目前正在开发的小型应用程序上运行良好.但它可能会影响另一个应用程序的性能.如果您真的只想禁用某些路由的视图重用,您可以查看设置 key
的值 基于路由.但我真的不喜欢这种方法.
However, this is an all-or-nothing solution. It seems to work well on the small application that I am currently developing. But it might have effects on performance in another application. If you really want to disable the reuse of the view for some routes only, you can have a look at setting the key
's value based on the route. But I don't really like that approach.
这篇关于使用 Vue Router 响应参数更改的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!