Faire défiler jusqu'aux ancres avec Vue Router
Dec 05 2020
J'ai besoin d'une configuration de lien d'ancrage dans vuejs pour accéder à:
<h1 id="apply">Test anchor</h1>
Ce qui suit fonctionne mais change l'URL en http: // localhost: 8080 / # / apply
<a href="#apply" class="btn btn-primary mt-3">Apply Now</a>
Si j'actualise ensuite la page, il ne sait pas où aller.
Ce qui suit ne fonctionne pas non plus pour moi. Cela ne revient même pas à #apply.
<router-link to="/careers/job-1#apply">test</router-link>
Comment configurer les liens d'ancrage avec le routage vuejs?
Réponses
1 Dan Dec 05 2020 at 07:51
Ajoutez un path
et une hash
propriété à votre to
objet:
<router-link :to="{ path: '/careers/job-1', hash: '#apply' }">test</router-link>
Et ajoutez scrollBehavior
à votre définition de routeur:
const router = new VueRouter({
...
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
};
}
return { x: 0, y: 0 }; // Go to the top of the page if no hash
},
...
})
Maintenant, il devrait défiler (en douceur, sauf si vous supprimez cette behavior
propriété) jusqu'à l'ancre définie par le hachage