How to create anchor tags with Vue Router

前端 未结 4 1984
半阙折子戏
半阙折子戏 2020-12-15 06:45

I am creating a small Vue webapp, I want to create an anchor tag in this.

I have given an id to one of the div I wanted to have anchor tags

4条回答
  •  不思量自难忘°
    2020-12-15 07:00

    I believe you are asking about jumping directly to a particular area of page, by navigating to an anchor tag like #section-3 within the page.

    For this to work, you need to modify your scrollBehavior function as follows:

    new VueRouter({
        mode: 'history',
        scrollBehavior: function(to, from, savedPosition) {
            if (to.hash) {
                return {selector: to.hash}
            } else {
                return { x: 0, y: 0 }
            }
        },
        routes: [
            {path: '/', component: abcView},
            // your routes
        ]
    });
    

    Ref: https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling

    I attempted creating a jsFiddle example but it is not working because of mode:'history'. If you copy the code and run locally, you will see how it works: https://jsfiddle.net/mani04/gucLhzaL/

    By returning {selector: to.hash} in scrollBehavior, you will pass the anchor tag hash to the next route, which will navigate to the relevant section (marked using id) in that route.

提交回复
热议问题