Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

310
Views
El enrutador Vue no busca corregir la ubicación del hash

Al hacer clic en un enlace en la aplicación, el enrutador no se desplaza a la ubicación hash correcta proporcionada. Pero SÍ se burla. El pergamino siempre está aproximadamente 1 elemento demasiado alto en la página. Por ejemplo, si mi página es esta:

 <template> <div id="div1">Div1</div> <div id="div2">Div2</div> <div id="div3">Div3</div> <div id="div4">Div4</div> </template>

Luego, si hago clic en un enlace que va al hash "div3", me desplazará hasta la parte superior de div2. Solo unos pocos elementos seleccionados se desplazan correctamente. ¿Hay alguna razón para esto? ¿Establecer márgenes de página?

Código del enrutador:

 const router = new VueRouter({ routes, mode: 'history', base: "/", scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash, behavior: 'smooth', } } else { return { x: 0, y: 0 } } } })

Ejemplo de código que llama al enrutamiento hash:

 if (item.title == "Mission") { router.push({name: 'Explore', hash: '#mission-statement'}); } else if (item.title == "Our Story") { router.push({name: 'Explore', hash: '#our-story-container'}); } else if (item.title == "Shared principles") { router.push({name: 'Explore', hash: '#shared-principles-container'}); } else if (item.title == "Volunteer Opportunities") { router.push({name: 'Explore', hash: '#volunteer-container'}); } else if (item.title == "Gallery") { router.push({name: 'Explore', hash: '#galleries'}); } else if (item.title == "Living") { router.push({name: 'Explore', hash: '#living-container'}); } else if (item.title == "Contact Us") { router.push({name: 'Explore', hash: '#contact-us-container'}); } else { router.push("/explore") }

SOLUCIÓN:

Con la ayuda de la respuesta de IVO GELOV, pude actualizar la función de comportamiento de desplazamiento con el siguiente código y todo funciona como se esperaba.

 scrollBehavior (to, from, savedPosition) { let position = {} if (to.hash) { position = { selector: to.hash, offset: { x: 0, y: 100 }, behavior: 'smooth', } } else { position = { x: 0, y: 0 } } return new Promise((resolve) => { setTimeout(() => { resolve(position) }, 100) }) }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Nuxt.js está utilizando el siguiente código en su ./nuxt/router.js ; quizás pueda adoptarlo para su caso de uso:

 import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) if (process.client) { window.history.scrollRestoration = 'manual' } const scrollBehavior = function (to, from, savedPosition) { // if the returned position is falsy or an empty object, // will retain current scroll position. let position = false // if no children detected if (to.matched.length < 2) { // scroll to the top of the page position = { x: 0, y: 0 } } else if (to.matched.some((r) => r.components.default.options.scrollToTop)) { // if one of the children has scrollToTop option set to true position = { x: 0, y: 0 } } // savedPosition is only available for popstate navigations (back button) if (savedPosition) { position = savedPosition } return new Promise(resolve => { // wait for the out transition to complete (if necessary) window.$nuxt.$once('triggerScroll', () => { // coords will be used if no selector is provided, // or if the selector didn't match any element. if (to.hash) { let hash = to.hash // CSS.escape() is not supported with IE and Edge. if (typeof window.CSS !== 'undefined' && typeof window.CSS.escape !== 'undefined') { hash = '#' + window.CSS.escape(hash.substr(1)) } try { if (document.querySelector(hash)) { // scroll to anchor by returning the selector position = { selector: hash } } } catch (e) { console.warn('Failed to save scroll position. Please add CSS.escape() polyfill (https://github.com/mathiasbynens/CSS.escape).') } } resolve(position) }) }) } export function createRouter () { return new Router({ mode: 'history', base: '/', linkActiveClass: 'nuxt-link-active', linkExactActiveClass: 'nuxt-link-exact-active', scrollBehavior, routes: [ .... ], fallback: false }) }

Una implementación de ejemplo (tomada de https://dev.to/dimer191996/nuxt-js-smooth-scrolling-with-hash-links-94a ): es posible que también deba configurar window.history.scrollRestoration = 'manual' si su <router-view> está envuelto dentro de una <transition> :

 scrollBehavior: async (to, from, savedPosition) => { if (savedPosition) { return savedPosition } const findEl = async (hash, x) => { return document.querySelector(hash) || new Promise((resolve, reject) => { if (x > 50) { return resolve() } setTimeout(() => { resolve(findEl(hash, ++x || 1)) }, 100) }) } if (to.hash) { let el = await findEl(to.hash) if ('scrollBehavior' in document.documentElement.style) { return window.scrollTo({ top: el.offsetTop, behavior: 'smooth' }) } else { return window.scrollTo(0, el.offsetTop) } } return { x: 0, y: 0 } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!