Home > OS >  Vue router - path #ID scrollBehavior
Vue router - path #ID scrollBehavior

Time:12-12

I have created a MENU where I link via <router-link> but certain links are linked to the same page using (anchors).
When I'm on the Work page and I click on the #services section, which is on the Bio page, the section is displayed correctly, but if I want to go to the services section on the Bio page, the URL just changes, but it won't go to the right section for me.

noubtest.com

NAVIGATION

<router-link v-show="!mobile"  :to="{ name: 'Home' }">Bio</router-link>
<router-link v-show="!mobile"  :to="{ name: 'Services' }">Services</router-link>
<router-link v-show="!mobile"  :to="{ name: 'SelectedWork' }">Work</router-link>

ROUTER

{
  path: "/home",
  name: "Home",
  component: Home,
  meta: {
    title: "Bio",
    requiresAuth: false,
  },
},
{
  path: "/home#fifthPage",
  name: "Services",
  component: Home,
  meta: {
    title: "Services",
    requiresAuth: false,
  },
},

const router = new VueRouter({
  mode: "history",
 
  routes,
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
});

router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title} | YounesFilm`;
  next();
});

router.beforeEach(async (to, from, next) => {
  let user = firebase.auth().currentUser;
  let admin = null;
  if (user) {
    let token = await user.getIdTokenResult();
    admin = token.claims.admin;
  }
  if (to.matched.some((res) => res.meta.requiresAuth)) {
    if (user) {
      if (to.matched.some((res) => res.meta.requiresAdmin)) {
        if (admin) {
          return next();
        }
        return next({ name: "Home" });
      }
      return next();
    }
    return next({ name: "Home" });
  }
  return next();
});

export default router;

How can I click through the page between sections?

CodePudding user response:

With a few research, I found two things that could help you.

First, this error is known and discussed on github vue-router issues page.

Second, I found that Workaround on npmjs.com, and you could probably give it a try.

CodePudding user response:

You must switch your VueRouter from hash mode to history mode of routing - then hashtags will work but in a different way.
Your routes should not have a hash symbol # inside their path - instead, you should provide it under the hash attribute of the route link:

<router-link :to="{ name: pathName, hash: '#text' }">
    Jump to content
</router-link>

But this alone is not enough. You also need to alter the scrollBehavior of the VueRouter:

import { routes } from './routes.js';

const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) 
    {
        if (savedPosition) 
        {
            return savedPosition;
        }
        if (to.hash) 
        {
            return { selector: to.hash }; // <==== the important part
        }
        return { x: 0, y: 0 };
    }
});
  • Related