UNPKG

@daysnap/vue-use

Version:
80 lines (79 loc) 3.3 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { isNumber, isUndefined } from '@daysnap/utils'; import { ref, watch } from 'vue'; import { useRoute } from 'vue-router'; const keepAliveList = ref(); // fix 解决 transform keep-alive bug 问题 // 二级keepalive 动画会有问题,这个延时需要根据动画时间来 const includes = ref([]); const getHistoryState = () => { var _a; return (_a = history.state) !== null && _a !== void 0 ? _a : {}; }; /** * 结合 KeepAlive 组件,维护其 includes */ export function useKeepAlive(options) { var _a; if (isUndefined(keepAliveList.value)) { keepAliveList.value = []; const route = useRoute(); watch(() => (Object.assign({}, route)), (to, from) => { var _a; const { position, replaced, scroll } = getHistoryState(); keepAliveList.value = ((_a = keepAliveList.value) !== null && _a !== void 0 ? _a : []).filter((item) => { const { mode, relations } = item; // 自定义 if (mode === 'custom') { return true; } // replace if (replaced && scroll === false) { // 有关联的 route if (relations === null || relations === void 0 ? void 0 : relations.length) { const formName = from.name; if (relations.includes(formName)) { const toName = to.name; return relations.includes(toName); } } return position > item.position; } return position >= item.position; }); }); const ms = isNumber(options) ? options : 0; watch(() => keepAliveList.value, (nv, ov) => { if (JSON.stringify(nv) !== JSON.stringify(ov)) { setTimeout(() => { var _a, _b; includes.value = (_b = (_a = keepAliveList.value) === null || _a === void 0 ? void 0 : _a.map((item) => item.name)) !== null && _b !== void 0 ? _b : []; }, ms); } }, { immediate: true, }); } if (!isNumber(options)) { const _b = useRoute(), { meta } = _b, rest = __rest(_b, ["meta"]); const { name, mode, relations } = Object.assign({ mode: 'auto' }, rest, meta, options); const { position = 0 } = getHistoryState(); if (name) { keepAliveList.value = [ ...((_a = keepAliveList.value) !== null && _a !== void 0 ? _a : []).filter((item) => item.name !== name), { position, name, mode, relations }, ]; } } return { keepAliveList, includes, }; }