Best Practice for Reacting to Params Changes with Vue Router

大城市里の小女人 提交于 2019-11-30 06:26:26

问题


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, ...
}

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.


回答1:


One possible answer that I just found thanks to a GitHub issue is the following.

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>

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.

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.



来源:https://stackoverflow.com/questions/40404787/best-practice-for-reacting-to-params-changes-with-vue-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!