vue.js “滚动到顶部"按钮不起作用,无法读取未定义的属性(阅读”scrollTo“)

hgncfbus  于 2023-03-19  发布在  Vue.js
关注(0)|答案(2)|浏览(208)

我正在尝试使用$refs. topScroll. scrollTo滚动到顶部按钮。当显示搜索列表并滚动到底部时,单击顶部按钮视图不会移动到块的顶部,显示无法读取未定义的属性(阅读“scrollTo”)错误。我正在尝试使用Alpinejs进行此操作,但我认为Vuejs也是如此。
https://codesandbox.io/s/html-template-forked-z453xs?file=/index.html

<!-- <!DOCTYPE html> -->
<html lang="en">
  <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" />
    <link rel="stylesheet" href="normalize.css" />
    <link rel="stylesheet" href="styles.css" />
    <script
      defer
      src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"
    ></script>
    <!-- <script type="”module”" src="./script.js"></script> -->
    <title>Vesna</title>
  </head>

  <body>
    <section class="content">
      <div class="container">
        <div
          class="content__top"
          x-data="{
          search: ''
        }"
        >
          <input
          />
          <button
            class="input__btn font--m1"
            @click="$store.products.getAllProducts(search)"
          >
            Search
          </button>
        </div>
        <div
          x-ref="topScroll"
        >
          <div x-data>
            <template x-for="item in $store.products.people" :key="item.id">
              <div class="content__mid">
                <p class="content__mid-item" x-text="item.name"></p>
                <p class="content__mid-item" x-text="item.email"></p>
              </div>
            </template>
          </div>
        </div>
        <div class="content__bottom">
          <div class="content__bottom-left">
            <div
              class="btn--content"
              x-data
              @click="$refs.topScroll.scrollTo({top: 0, behavior: 'smooth'})"
            >
              <span class="font--m1 text-underline">to top</span>
            </div>
           
        </div>
      </div>
    </section>

    <script>
      document.addEventListener("alpine:init", () => {
        Alpine.store("products", {
          people: [],
          showTableHeader: false,
          index: 0,
          step: 5,

          getAllProducts(searchInput) {
            fetch("https://jsonplaceholder.typicode.com/users")
              .then((response) => response.json())
              .then((res) => {
                this.people = res;
                this.showTableHeader = true;
                console.log(this.showTableHeader);
              });
          }
        });
      });
    </script>
  </body>
</html>
ni65a41a

ni65a41a1#

您使用的$refs.topScroll可能无法正常工作,因此最好使用window.scrollTo

<div class="btn--content" x-data @click="window.scrollTo({top: 0, behavior: 'smooth'})">
   <span class="font--m1 text-underline">to top</span>
</div>
zpqajqem

zpqajqem2#

@click=“窗口.文档.查询选择器('. content__mid-wrapper').滚动到({顶部:0,行为:'平滑'})”

相关问题