0x30/vue-navigation

怎么记录滚动位置

Closed this issue · 7 comments

我有一个嵌套的视图组件

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: layout,
      children: [
        {
          path: '',
          component: Home,
          meta: {
            title: 'home',
          },
        },
        {
          path: 'about',
          name: 'About',
          component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
          meta: {
            title: 'about',
          },
        },
      ],
    },
  ],
});
  • view
<template>
  <div class="page">
    <div class="page-header">{{ title }}</div>
    <div class="page-main">
      <router-view v-slot="{ Component, route }">
        <Navigation>
          <component
            :is="Component"
            :key="route.meta.usePathKey ? route.path : undefined"
          />
        </Navigation>
      </router-view>
    </div>
    <div class="page-footer"></div>
  </div>
</template>

我想让不同的页面滚动条位置都可以正确的展示,有什么好的方法吗

0x30 commented
import {
  defineComponent,
  HTMLAttributes,
  onActivated,
  reactive,
  ref
} from "vue";
import Style from "./ScrollBody.module.scss";

export default defineComponent({
  name: "ScrollBody",
  setup: (props: HTMLAttributes, { slots }) => {
    const mainDiv = ref<HTMLElement | null>(null);
    const offset = reactive({ left: 0, top: 0 });

    const onScrollHandle = (event: UIEvent) => {
      if (event.target instanceof HTMLElement) {
        offset.top = event.target.scrollTop;
        offset.left = event.target.scrollLeft;
      }
      props.onScroll?.(event);
    };

    onActivated(() => {
      if (mainDiv.value === null || (offset.top === 0 && offset.left === 0))
        return;
      mainDiv.value.scroll({ left: offset.left, top: offset.top });
    });

    return () => {
      return (
        <main onScroll={onScrollHandle} ref={mainDiv} class={Style.scrollView}>
          {slots.default?.()}
        </main>
      );
    };
  }
});

我一般会把应用中用到的滑动部分,单独做成一个组件,由它自己管理自己的滑动位置

直接上生产项目,抛出了两个警告

injection "Symbol([vue-router]: router)" not found. 
 Unhandled error during execution of setup function 

然后抛出了一个错误

ypeError: Cannot read property '___0x30_navigation_listened' of undefined

切图仔,没时间看源码,能指点一下吗

0x30 commented

给一个复现的例子?这样我也不好找,或者看下例子

稍等,我复制一份最小的例子给你

老哥有啥进展没

0x30 commented

最近一直在忙
我这个项目一般只用在移动端h5,之前没考虑过嵌套路由的事儿,所以一时想不起来有哪里问题。
等后续有时间我再看一下,有啥进展这里同步
你也可以看一下,代码比较简单 就一组件