Skip to content

Commit

Permalink
fix: refactor destroy methods for a nested using & update example
Browse files Browse the repository at this point in the history
  • Loading branch information
barrier committed Apr 7, 2022
1 parent 282cf40 commit 04a546c
Show file tree
Hide file tree
Showing 9 changed files with 98 additions and 61 deletions.
31 changes: 13 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,29 +126,24 @@ export default {

### 销毁页面缓存

$routeHistory.destroy
$routerHistoryInstance.destroy

```javascript
// 通过path销毁相应页面缓存
// 使用时请避免销毁当前页面的缓存,以免引起页面渲染问题
destroyByPath() {
const res = this.$routerHistory.destroy({ path: '/home/list' });
const res = this.$routerHistoryInstance.destroy({ path: '/home/list' });
// res为true表示销毁成功,否则销毁失败
},
// 通过cacheKey销毁相应页面缓存
destroyByCacheKey() {
const routeHistory = history.state.routeHistory || [];
const key = routeHistory.slice(-2)[0].cacheKey; // 从路由历史中获取对应页面的cacheKey
const res = this.$routerHistory.destroy({ key });
// 同上
}
```

$routeHistory.destroyAll
$routerHistoryInstance.destroyAll

```javascript
// 销毁所有页面缓存
// destroyAll方法不会销毁当前页面的缓存
destroyAll() {
this.$routerHistory.destroyAll();
this.$routerHistoryInstance.destroyAll();
}
```

Expand All @@ -170,7 +165,7 @@ index.vue(父页面)
</template>
```

index.vue(子页面,route-name: keep-scroll)
index.vue(子页面,例如:route-name: keep-scroll)

```vue
<template>
Expand Down Expand Up @@ -198,12 +193,12 @@ export default [

### routes meta 参数

| 参数 | 描述 | 类型 | 默认值 |
| -------------- | ---------------------------------------------------------------------------------------- | ------- | ------- |
| aliveKey | 嵌套使用`<history-keep-alive>`时,想要在不同页面复用相同的父级组件,就要设置一个唯一的值 | String | |
| nocache | 是否禁用缓存 | Boolean | |
| transitionName | 设置页面的 transition 效果,可选值`[slide, zoom, fade, fade-transform]` | String | 'slide' |
| keepScroll | 启用页面的 keep scroll | Boolean | |
| 参数 | 描述 | 类型 | 默认值 |
| -------------- | ---------------------------------------------------------------------------------------- | ------- | ------ |
| aliveKey | 嵌套使用`<history-keep-alive>`时,想要在不同页面复用相同的父级组件,就要设置一个唯一的值 | String ||
| nocache | 是否禁用缓存 | Boolean ||
| transitionName | 设置页面的 transition 效果,可选值`[slide, zoom, fade, fade-transform]` | String | |
| keepScroll | 启用页面的 keep scroll 功能 | Boolean ||

**[demo](https://github.com/yang862/history-keep-alive-example/blob/master/src/transition/router/main.js)**

Expand Down
4 changes: 4 additions & 0 deletions examples/develop/src/keep-alive/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
<meta http-equiv="Cache" content="no-cache">
<title>history-keep-alive example</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<!-- <script src="https://cdn.bootcss.com/vConsole/3.2.2/vconsole.min.js"></script>
<script type="text/javascript">
var vConsole = new VConsole();
</script> -->
</head>

<body>
Expand Down
40 changes: 22 additions & 18 deletions examples/develop/src/keep-alive/views/destroy/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,36 @@
<span @click="destroy">
<van-icon name="browsing-history" color="#3F93DC" size="30px" />
<div>通过path销毁指定页面缓存</div>
<div style="font-size:12px;">调用this.$routerHistory.destroy方法</div>
<div style="font-size:12px;">
<div>调用this.$routerHistoryInstance.destroy方法</div>
<div>
<span style="font-weight:bold;">注:</span>
请避免销毁当前页面的缓存,以免引起页面渲染问题
</div>
</div>
</span>
</van-col>
</van-row>
<van-row justify="space-between" style="padding-top:20px;">
<van-col span="24" style="text-align:center;">
<span @click="destroyByCacheKey">
<span @click="destroyAll">
<van-icon name="browsing-history" color="#3F93DC" size="30px" />
<div>通过cacheKey销毁指定页面缓存</div>
<div style="font-size:12px;">调用this.$routerHistory.destroy方法</div>
<div>销毁所有页面缓存</div>
<div style="font-size:12px;">
<div>调用this.$routerHistoryInstance.destroyAll方法</div>
<div>
<span style="font-weight:bold;">注:</span>
destroyAll方法不会销毁当前页面的缓存
</div>
</div>
</span>
</van-col>
</van-row>
<van-row justify="space-between" style="padding-top:20px;">
<van-col span="24" style="text-align:center;">
<span @click="destroyAll">
<van-icon name="browsing-history" color="#3F93DC" size="30px" />
<div>销毁所有页面缓存</div>
<div style="font-size:12px;">调用this.$routerHistory.destroyAll方法</div>
<span @click="()=>$router.push({name:'home'})">
<van-icon name="wap-home" color="#3F93DC" size="30px" />
<div>跳转首页</div>
</span>
</van-col>
</van-row>
Expand All @@ -47,21 +58,14 @@ export default {
},
methods: {
destroy() {
const res = this.$routerHistory.destroy({ path: '/home/list' });
res ? this.$toast.success('销毁首页成功!')
: this.$toast.fail('销毁首页失败,未找到对应的缓存!');
},
destroyByCacheKey() {
const routeHistory = history.state.routeHistory || [];
const key = routeHistory.slice(-2)[0].cacheKey; // 从路由历史中获取对应页面的cacheKey
const res = this.$routerHistory.destroy({ key });
const res = this.$routerHistoryInstance.destroy({ path: '/home/list' });
res ? this.$toast.success('销毁首页成功!')
: this.$toast.fail('销毁首页失败,未找到对应的缓存!');
},
destroyAll() {
this.$routerHistory.destroyAll();
this.$routerHistoryInstance.destroyAll();
this.$toast.success('销毁所有页面完成!');
}
},
}
}
</script>
2 changes: 1 addition & 1 deletion examples/develop/src/keep-alive/views/detail/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ export default {
return {
count: 0,
}
}
},
}
</script>
30 changes: 29 additions & 1 deletion examples/develop/src/keep-alive/views/frame-detail/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,33 @@
</van-col>
<van-col span="12" style="text-align:center;">
<span @click="()=>$router.push({name:'home'})">
<van-icon name="chat" color="#3F93DC" size="30px" />
<van-icon name="wap-home" color="#3F93DC" size="30px" />
<div>跳转首页</div>
</span>
</van-col>
</van-row>
</div>
<div v-if="!isDetail" class="card" style="margin-top:20px;">
<van-row justify="space-between">
<van-col span="24" style="text-align:center;">
<span @click="destroyNested">
<van-icon name="browsing-history" color="#3F93DC" size="30px" />
<div>销毁嵌套路由的指定页面缓存</div>
<div style="font-size:12px;">
<div>调用this.$routerHistoryInstance.destroy方法</div>
<div style="padding-top:10px;">
<span style="font-weight:bold;">注:</span>
单个
<span style="color:#3F93DC">history-keep-alive组件</span>
对自己的缓存独立进行管理,所以在子组件下调用destroy方法,只能销毁其所属的
<span style="color:#3F93DC">history-keep-alive组件</span>
的缓存
</div>
</div>
</span>
</van-col>
</van-row>
</div>
</div>
</div>
</template>
Expand All @@ -47,5 +68,12 @@ export default {
return this.$route.name === 'frame-detail';
}
},
methods: {
destroyNested() {
const res = this.$routerHistoryInstance.destroy({ path: '/frame/frame-detail' });
res ? this.$toast.success('销毁详情页面成功!')
: this.$toast.fail('销毁详情页面失败,未找到对应的缓存!');
},
}
}
</script>
2 changes: 1 addition & 1 deletion examples/develop/src/keep-alive/views/frame/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ export default {
return {
count: 0,
};
}
},
}
</script>
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "history-keep-alive",
"version": "0.1.7",
"version": "0.1.8",
"description": "vue plugin: keep alive like a native app, according to vue-router history",
"main": "dist/index.js",
"scripts": {
Expand Down
40 changes: 26 additions & 14 deletions packages/components/base-keep-alive/KeepAlive.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,14 @@ function pruneCacheEntry(
current
) {
const entry = cache[key];
if (entry && (!current || entry.tag !== current.tag)) {
if (entry && (!current || (entry.tag !== current.tag
|| entry.componentInstance._uid !== current.componentInstance._uid))) {
entry.componentInstance.$destroy();
cache[key] = null;
entry && remove(keys, key);
return true;
}
remove(keys, key);
return !!entry;
return false;
}

const patternTypes = [ String, RegExp, Array ];
Expand All @@ -92,11 +94,14 @@ export default {
if (!key) key = this.keyMap[path];
if (!key) return false;
if (path) this.keyMap[path] = null; // 清除keyMap
return pruneCacheEntry(this.cache, key, this.keys);
return pruneCacheEntry(this.cache, key, this.keys, this._vnode);
},
destroyAll() {
/**
* @param {Boolean} all 是否销毁所有组件缓存(包括当前组件)
*/
destroyAll(all) {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys);
pruneCacheEntry(this.cache, key, this.keys, all ? undefined : this._vnode);
}
},
cacheVNode() {
Expand Down Expand Up @@ -134,24 +139,24 @@ export default {
this.cache = Object.create(null);
this.keyMap = Object.create(null); // 用于以path对照key
this.keys = [];
if (this.$routerHistory) {
this.$routerHistory.destroy = this.destroy;
this.$routerHistory.destroyAll = this.destroyAll;
}
},

destroyed() {
this.destroyAll();
this.destroyAll(true);
},

mounted() {
this._setParentNode();
this.cacheVNode();
this.$watch('include', val => {
pruneCache(this, name => matches(val, name), !!this.aliveKey);
setTimeout(() => { // 等待页面渲染完成
pruneCache(this, name => matches(val, name), !!this.aliveKey);
}, 0);
});
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name), !!this.aliveKey);
setTimeout(() => { // 等待页面渲染完成
pruneCache(this, name => !matches(val, name), !!this.aliveKey);
}, 0);
});
},

Expand All @@ -173,6 +178,14 @@ export default {

const componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
setTimeout(() => { // 等待组件初始化完成
// 给<history-keep-alive>实例注入detroy方法
vnode.componentInstance.$routerHistoryInstance = {
destroy: this.destroy,
destroyAll: this.destroyAll,
};
}, 0);

// check pattern
const name = this.aliveKey || getComponentName(componentOptions);

Expand All @@ -182,7 +195,6 @@ export default {
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key);
this.$routerHistory.cacheKey = key; // 传递cacheKey

const { include, exclude } = this;
if (
Expand Down
8 changes: 1 addition & 7 deletions packages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ class RouterHistory {
routeName: null,
matched: [], // 当前展示的路由信息(嵌套多级)
timestamp: null,
cacheKey: null,
};
}
createHistory(to, timestamp) {
Expand All @@ -30,9 +29,8 @@ class RouterHistory {
return current;
}

addHistory({ router, routeHistory, isReplace = false, timestamp, cacheKey }) {
addHistory({ router, routeHistory, isReplace = false, timestamp }) {
const current = this.createHistory(router.currentRoute, timestamp);
if (cacheKey) current.cacheKey = cacheKey;
!isReplace ? routeHistory.push(current) : routeHistory.splice(-1, 1, current);
history.replaceState({ ...(history.state || {}), current, routeHistory }, '');
}
Expand Down Expand Up @@ -64,7 +62,6 @@ class RouterHistory {
timestamp: useTimestamp && router.currentRoute.query
? router.currentRoute.query.timestamp
: null,
cacheKey: _history.cacheKey,
});
}, 0);
});
Expand All @@ -74,7 +71,6 @@ class RouterHistory {
popstate: false,
immediate,
useTimestamp,
cacheKey: null,
defaultTransitionName,
};

Expand All @@ -101,7 +97,6 @@ class RouterHistory {
that.addHistory({
router, routeHistory, isReplace: true,
timestamp: useTimestamp ? timestamp : null,
cacheKey: _history.cacheKey,
});
};

Expand All @@ -115,7 +110,6 @@ class RouterHistory {
that.addHistory({
router, routeHistory,
timestamp: useTimestamp ? timestamp : null,
cacheKey: _history.cacheKey,
});
};

Expand Down

0 comments on commit 04a546c

Please sign in to comment.