chore(BackTop): only print error msg in development (#11310)

This commit is contained in:
neverland 2022-11-26 21:06:20 +08:00 committed by GitHub
parent a318807eb5
commit 41f35b2735
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -13,7 +13,6 @@ import {
// Utils // Utils
import { import {
addUnit, addUnit,
isObject,
inBrowser, inBrowser,
getScrollTop, getScrollTop,
createNamespace, createNamespace,
@ -53,10 +52,10 @@ export default defineComponent({
setup(props, { emit, slots, attrs }) { setup(props, { emit, slots, attrs }) {
const show = ref(false); const show = ref(false);
const scrollParent = ref<Window | HTMLElement>(); const root = ref<HTMLElement>();
const root = ref<HTMLElement | null>(null); const scrollParent = ref<Window | Element>();
let target: Window | HTMLElement; let target: Window | Element | undefined;
const style = computed(() => ({ const style = computed(() => ({
right: addUnit(props.right), right: addUnit(props.right),
@ -65,34 +64,34 @@ export default defineComponent({
const onClick = (event: MouseEvent) => { const onClick = (event: MouseEvent) => {
emit('click', event); emit('click', event);
target.scrollTo({ target?.scrollTo({
top: 0, top: 0,
behavior: 'smooth', behavior: 'smooth',
}); });
}; };
const scroll = () => { const scroll = () => {
show.value = getScrollTop(target) >= props.offset; show.value = target ? getScrollTop(target) >= props.offset : false;
}; };
const getTarget = () => { const getTarget = () => {
const { target } = props; const { target } = props;
if (typeof target === 'string') { if (typeof target === 'string') {
const el = document.querySelector(props.target as string); const el = document.querySelector(target);
if (!el) {
throw Error('[Vant] BackTop: target element is not found.'); if (el) {
} return el;
return el as HTMLElement;
} }
if (isObject(target)) { if (process.env.NODE_ENV !== 'production') {
return target; console.error(
} `[Vant] BackTop: target element "${target}" was not found, the BackTop component will not be rendered.`
throw Error(
'[Vant] BackTop: type of prop "target" should be a selector or an element object'
); );
}
} else {
return target as Element;
}
}; };
useEventListener('scroll', throttle(scroll, 100), { target: scrollParent }); useEventListener('scroll', throttle(scroll, 100), { target: scrollParent });
@ -100,9 +99,7 @@ export default defineComponent({
onMounted(() => { onMounted(() => {
nextTick(() => { nextTick(() => {
if (inBrowser) { if (inBrowser) {
target = props.target target = props.target ? getTarget() : getScrollParent(root.value!);
? (getTarget() as typeof target)
: (getScrollParent(root.value!) as typeof target);
scrollParent.value = target; scrollParent.value = target;
} }
}); });