简体   繁体   中英

Direct url with hash value does not work with vue-router

Navigating to url: site.com/#locallink 'redirects' to site.com, first time entered in the browser - in other words, does not jump to the anchor. If I simply re-type the url (site.com/#locallink) then it works as expected (jumps to anchor).

I have defined routes and router like so, and history mode as you can see.

 let router = new VueRouter({
        mode: 'history',
        scrollBehavior: function (to, from, savedPosition) {
            if (to.hash) {
                return { selector: to.hash }
            } else {
                return { x: 0, y: 0 }
            }
        },
        routes
    });

If I have a link on another page to the same anchor, then it works flawlessly. It's only when typed into the browser directly that it does not seem to work - the # part of it get's eaten.

The routes follow this pattern:

export const routes = [
     {
    path: '/',
    name: 'home',
    component: require('components/prelogin/landingpage.vue'),
    meta: {
        title: 'Some title',
        metaTags: [
            {
                name: 'title',
                content: '...'
            },
            {
                name: 'description',
                content: 'some description here...'
            }
        ]
    }
},
...

There are many entries so only showing first.

Any ideas? Thanks

Hope it will help

scrollBehavior: function (to, from, savedPosition) {
    if (to.hash){
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve({
                        selector: to.hash,
                        behavior: 'smooth',
                    })
                }, 500)
            })
    } else {
            return { x: 0, y: 0 }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM