【问题标题】:How to scroll to element in v-if with VueJS?如何使用 VueJS 滚动到 v-if 中的元素?
【发布时间】:2021-05-18 13:29:33
【问题描述】:

在我的 Vue 3 项目中,我在一个组件中有这个按钮:

<template>
  <button type="button" class="btn btn-success" :data-id="product.id"
    v-on:click="hideButtonAndScroll(product.id)">Get Offer</button>

  <!-- ... some code here ... -->

  <offer-form :product="product"></offer-form>
</template>

<script>
export default {
  props: ['products'],
  data() {
    return { visibleFormId: 0 };
  },
  methods: {
    hideButtonAndScroll(id) {
      this.visibleFormId = id;
      window.scrollTo({
        top: document.getElementById('product-id-' + id).offsetTop,
        left: 0,
        behavior: 'smooth',
      });
    }
  },
}
</script>

OfferForm.vue 文件中,我有这个 HTML 代码:

<template>
  <div :id="'product-id-' + product.id">
    <!-- ... -->
  </div>
</template>

问题是当我调用document.getElementById('product-id-' + id) 函数时,实际上该元素还不存在。

有没有办法等到渲染完成?然后开始滚动?

【问题讨论】:

  • 加载数据后从 OfferForm.vue 发出事件,并在将执行滚动的父 vue 上监听它。

标签: javascript vue.js vue-component vuejs3 js-scrollto


【解决方案1】:

您可以等到使用await this.$nextTick() 的下一个渲染周期来查看更改visibleFormId 的任何副作用(使用下面的async/await):

export default {
  methods: {
  ?async hideButtonAndScroll(id) {
      this.visibleFormId = id;

    ?await this.$nextTick();

      window.scrollTo({
        top: document.getElementById('product-id-' + id).offsetTop,
        left: 0,
        behavior: "smooth",
      });
    },
  },
}

demo

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2020-08-12
    • 2022-07-15
    • 2019-05-30
    • 2020-03-29
    • 2018-05-10
    相关资源
    最近更新 更多