UNPKG

@daysnap/vue-use

Version:
69 lines (68 loc) 2.69 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 { ref, watch, computed } from 'vue'; import { useRoute } from 'vue-router'; import { isUndefined, isBoolean } from '@daysnap/utils'; const keepAliveList = ref(); const setState = (state, ms = 0) => { // fix 解决 vite 热更新触发多次更新 if (JSON.stringify(state) !== JSON.stringify(keepAliveList.value)) { // fix 解决 transform keep-alive bug 问题 setTimeout(() => (keepAliveList.value = state), ms); } }; const keep = (data) => { var _a; const { name } = data; const list = [...((_a = keepAliveList.value) !== null && _a !== void 0 ? _a : []).filter((item) => item.name !== name), data]; setState(list); }; const includes = computed(() => keepAliveList.value.map((item) => item.name)); const getState = () => { var _a; return (_a = history.state) !== null && _a !== void 0 ? _a : {}; }; /** * 结合 KeepAlive 组件,维护其 includes * @deprecated 目前因为有路由会产生BUG,已经过期,后期版本会删除掉,请使用 useKeepAlive 方法 */ export function useKeepAliveByPosition(options) { if (isUndefined(keepAliveList.value)) { keepAliveList.value = []; const route = useRoute(); watch(() => (Object.assign({}, route)), (_, from) => { var _a; const { position, replaced } = getState(); const list = ((_a = keepAliveList.value) !== null && _a !== void 0 ? _a : []).filter((item) => { const { mode, name } = item; if (mode === 'custom') { return true; } if (replaced && from.name === name) { return false; } return position >= item.position; }); setState(list, 300); }); } if (!isBoolean(options)) { const _a = useRoute(), { meta } = _a, rest = __rest(_a, ["meta"]); const { name, mode } = Object.assign({ mode: 'auto' }, rest, meta, options); const { position = 0 } = getState(); if (name) { keep({ position, name: name, mode }); } } return { keepAliveList, includes, keep, }; }