@daysnap/vue-use
Version:
daysnap vue hooks
41 lines (40 loc) • 1.42 kB
JavaScript
import { pick } from '@daysnap/utils';
import { onActivated, nextTick, ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';
export function useKeepPosition(options = {}) {
const { selectors } = options;
const state = ref();
// 获取需要恢复位置的元素
const getTarget = () => {
var _a, _b;
return (_b = (_a = options.getTarget) === null || _a === void 0 ? void 0 : _a.call(options)) !== null && _b !== void 0 ? _b : (selectors ? document.querySelector(selectors) : document.documentElement);
};
// 保存位置
const keep = () => {
const target = getTarget();
if (target) {
state.value = pick(target, ['scrollTop', 'scrollLeft']);
}
};
// 恢复
const restore = () => {
nextTick(() => {
var _a;
const target = getTarget();
if (target) {
const { scrollLeft = 0, scrollTop = 0 } = (_a = state.value) !== null && _a !== void 0 ? _a : {};
state.value = undefined;
const setScroll = () => {
target.scrollLeft = scrollLeft;
target.scrollTop = scrollTop;
};
setScroll();
}
});
};
// 保存位置
onBeforeRouteLeave(() => keep());
// 恢复位置
onActivated(() => restore());
return { keep, restore };
}