-
router-view组件有无key的区别(router-view已被keep-alive包裹)
-
无key:不同路由配置的组件相同时,这些路由会共用同一个组件实例。(通常做法)
-
有key:不同路由配置的组件相同时,每个路由对应一个自己的实例。(需要用一个组件创建多个路由,同时又希望这几个页面相互独立、互不影响)
-
-
有key的常规写法:
<keep-alive> <router-view :key="routeKey" /> </keep-alive> ---分割线--- computed: { routeKey() { return this.$route.path }, },
-
有key的注意事项
-
问题:这个有key的router-view可能会创建出多余的组件实例,导致内存泄漏。
-
产生原因:新的路由导航结束时,如果这个有key的router-view未被激活(通常这种情况会发生在有key的router-view层级较深,而当前路由层级较浅),则这个router-view仍然会以当前的新key创建一个组件实例(所创建的组件实例为此router-view最后一次渲染的组件)。
-
解决方案:限制router-view所绑定key的值的区间为所有可激活此router-view的路由的path。
-
示例代码:
<keep-alive> <router-view :key="routeKey" /> </keep-alive> ---分割线--- data(){ return { currentRoute: '' } }, computed:{ routeKey(){ if(this.$route.path.startsWith('/insight/')){ this.currentRoute= this.$route.path return this.$route.path }else{ return this.currentRoute } } },
-
router-view组件绑定key的作用、注意事项
于 2022-07-01 19:03:19 首次发布