首页 > 解决方案 > $vuetify.goTo('#foo') 不在另一个路由器页面上工作

问题描述

我尝试使用 Vuetify 提供的函数 goTo("#how") 平滑滚动。它工作正常,但是当我转到不同的路由器页面时,它会出错。

[Vue 警告]:v-on 处理程序中的错误:“错误:未找到目标元素“#how”。”

据我所知,这意味着目标元素不存在。

我尝试更改 goTo("/#how"), goTo("/how") 但似乎没有希望。

//App.vue where the header, footer of my app exist and the button that calls the function: goTo() 
<v-btn @click="() => this.$vuetify.goTo('#how')">How it Works</v-btn>
//The section where the page should scroll when the button is clicked
<section id="how">
</section>
//the goTo scroll function provided by Vuetify
scrollBehavior: (to, from, savedPosition) => {
  let scrollTo = 0

  if (to.hash) {
      scrollTo = to.hash
  } else if (savedPosition) {
      scrollTo = savedPosition.y
  }

  return goTo(scrollTo)
}

我希望在另一个路由页面上单击按钮时,它应该平滑滚动到该部分。

标签: vue.jsvuetify.js

解决方案


所以,我找到了解决我的问题的方法。这可能不是最干净的方式,但它确实有效。

我的解决方案是为按钮添加条件语句。

//First check if the current route is on landing page (or wherever your #foo is) then set the click function for it.
<v-btn v-if='this.$route.path == "/"' color="white" @click="() => this.$vuetify.goTo('#foo')" flat>How it Works</v-btn>

//If route.path is not at "/" then we call the router push to redirect first to Landing and then scroll.
<v-btn v-else color="white" @click="() => this.$router.push('/#foo')" flat>How it Works</v-btn>

推荐阅读