vue+TS锚点跳转

项目时vue+ts,导航栏是一个组件,其中有个多级子菜单点击要实现某个菜单锚点跳转,怎么搞?

网上都说可以这样

private jumpTo(path: ""): void {
    if (document.querySelector("#" + path))
    <HTMLElement>document.querySelector("#" + path).scrollIntoView(true);
  }

8029e4d75b0436773dd118520bc3cea.png

但获取dom这条语句错误!关于ts操作dom我也一直没弄明白,我该从哪里了解这方面知识呢?

阅读 3.9k
2 个回答

document.querySelector 在 TS 看来可能返回值为 null,你需要加下非空断言操作符:

(<HTMLElement>document.querySelector("#" + path))!.scrollIntoView(true);

贴一下我最后跳转的实现,总感觉不优雅,有更好的方式还请各位不吝赐教

headerNav.vue


  private jumpTo(p: ""): void {
    if (this.$route.fullPath !== "/services") {
      this.$router.push({ name: "services" });
      setTimeout(() => {
        this.anchorJump(p);
      }, 0);
    } else {
      console.log(p);
      this.anchorJump(p);
    }
    // this.$router.push({ name: "services", params: { path: p } });
    // if (document.querySelector("#" + path))
    // console.log(document.querySelector("#" + p));
    // (<HTMLElement>document.querySelector("#" + p))!.scrollIntoView(true);
  }
  private anchorJump(anchor: string): void {
    if (anchor) {
      const href = document.createElement("a");
      href.setAttribute("href", "#" + anchor);
      console.log(document.getElementsByClassName("contact-us")[0]);
      document.getElementsByClassName("contact-us")[0].appendChild(href);
      href.click();
      setTimeout(() => {
        document.getElementsByClassName("contact-us")[0].removeChild(href);
      }, 0);
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题