How can vue-router push({name:"question"}) with hash?

Viewed 17529
3 Answers

Vue Router allows you to completely customize the scroll behavior on route navigation. Vue scroll behavior is a wide topic, so you can dive into docs

For your example I think you need hash prop, with scroll behavior:

Router.push({ name: routeName, hash: '#toHash' })

router.push({ name: 'question', hash: '#hello' }) can work

For Router.push({ name: routeName, hash: '#toHash' }) to work, you need to configure your vue router.

// router.js file
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    // Your Routes
  ],
  // Ref: https://router.vuejs.org/guide/advanced/scroll-behavior.html
  scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      // This ensures that if hash is provided to router.push it works as expected.
      //  & since we have used "behavior: 'smooth'" the browser will slowly come to this hash position.
      return {
        el: to.hash,
        behavior: 'smooth',
      }
    }
  }
});

This code assumes you are using vue-router v4.

Related