使用 vue-router 保留组件状态? [英] Preserve component state with vue-router?

查看:39
本文介绍了使用 vue-router 保留组件状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表/详细信息用例,用户可以双击产品列表中的项目,转到详细信息屏幕进行编辑,然后在完成后返回列表屏幕.我已经使用此处描述的动态组件技术完成了此操作:https://vuejs.org/v2/guide/components.html#Dynamic-Components.但是现在我打算在应用程序的其他地方使用 vue-router,我想重构它以使用路由.使用我的动态组件技术,我使用 keep-alive 来确保当用户切换回列表视图时,出现与编辑之前相同的选择.但在我看来,路由产品列表组件会重新呈现,这不是我想要的.

I have a listing/detail use case, where the user can double-click an item in a product list, go to the detail screen to edit and then go back to the listing screen when they're done. I've already done this using the dynamic components technique described here: https://vuejs.org/v2/guide/components.html#Dynamic-Components. But now that I'm planning to use vue-router elsewhere in the application, I'd like to refactor this to use routing instead. With my dynamic components technique, I used keep-alive to ensure that when the user switched back to the list view, the same selection was present as before the edit. But it seems to me that with routing the product list component would be re-rendered, which is not what I want.

现在,路由器视图似乎可以包含在 keep-alive 中,这将解决一个问题,但会引入很多其他问题,因为我只希望该路由保持活动状态,而不是所有这些(目前我仅使用单个顶级路由器视图).Vue 2.1 通过为路由器视图引入包含和排除参数,显然已经做了一些事情来解决这个问题.但我也不想这样做,因为必须在我的主页中预先声明所有应该或不应该使用 keep-alive 的路由似乎很笨拙.在配置路由时(即在路由数组中)声明是否要保持活动状态会更简洁.那么我最好的选择是什么?

Now, it looks like router-view can be wrapped in keep-alive, which would solve one problem but introduce lots of others, as I only want that route kept alive, not all of them (and at present I'm just using a single top level router-view). Vue 2.1 has clearly done something to address this by introducing include and exclude parameters for router-view. But I don't really want to do this either, as it seems very clunky to have to declare up front in my main page all the routes which should or shouldn't use keep-alive. It would be much neater to declare whether I want keep-alive at the point I'm configuring the route (i.e., in the routes array). So what's my best option?

推荐答案

你可以指定你想要存活的路由,比如:

You can specify the route you want to keep alive , like:

<keep-alive include="home">
  <router-view/>
</keep-alive>

在这种情况下,只有回家的路线会保持活动

In this case, only home route will be kept alive

这篇关于使用 vue-router 保留组件状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆