vue中使用锚点

vue中直接使用锚点这个功能在没有引入vue-router之前是没有问题的,引入vue-router之后在未开启history模式的情况下会被视为路由的一部分。

这个时候再想使用锚点功能就不能直接用<a href="#name"></a>这种方式了,而是使用scrollIntoView方法进行锚点的跳转。

以下是源码:

<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
        <script src="https://unpkg.com/vue-router@3.5.4/dist/vue-router.js"></script>
    </head>
    <body>
        <div id="app">
            <li>
                <a href="javascript:void(0)" @click="goAnchor('tag')">跳转到目标位置</a>
            </li>
            <div style="height: 2000px;"></div>
            <a name="tag" id="tag">目标位置</a>
        </div>


        <script>
            const Foo = {
                template: `<div>Foo</div>`,
            }
            const routes = [{
                path: '/foo',
                component: Foo
            }]
            const router = new VueRouter({
                routes // (缩写) 相当于 routes: routes
            })
            const app = new Vue({
                router,
                data: {},
                methods: {
                    goAnchor(e) {
                        var id = "#" + e;
                        document.querySelector(id).scrollIntoView({
                            behavior: "smooth",
                            block: "center",
                            inline: "nearest",
                        });
                    },
                },
            }).$mount("#app")
        </script>

    </body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在项目中,最简单最直接的锚点定位跳转的方式就是要给点击的a标签的href属性上,加上要跳转的内容对应的id,实现浏...
    苏日俪格阅读 5,400评论 0 0
  • 最近又在vue中捣鼓了下微信公众号api的接入,不得不说这里边水是真的深啊,上次分享了微信授权登录和js-sdk签...
    imwty阅读 16,772评论 2 15
  • 前提 安装Js 方法1:下载vue.js文件,保存在js目录下方法2:采用npm方式 $ npm install ...
    coderlu阅读 506评论 0 1
  • 前沿 置身世外只为暗中观察!!!Hello大家好,我是魔王哪吒!重学巩固你的Vuejs知识体系,如果有哪些知识点遗...
    lessonSam阅读 1,210评论 0 13
  • 一、什么是Vue.js 1. vue是一种数据驱动的前端框架 this.msg="我爱你",通过改变数据,然后自动...
    在路上919阅读 1,664评论 0 2