滚动到 vue3 组合 API 中的元素

问题描述 投票:0回答:1

我需要在单击按钮后滚动到 v-if div,但这不起作用。我尝试如下参考方法:

import { onMounted } from 'vue';
export default {
  setup(context) {
    const confirmed = ref(false);
    const feedback = ref(null);

    function confirmSelection() {
      confirmed.value = true;
      
      this.$nextTick(() => {
        feedback.value.scrollIntoView({ behavior: "smooth", block: "center" });
      });      
    }

    onMounted( () => {
        feedback.value = document.getElementById("feedback");
    })

    return {
      confirmed,
      confirmSelection,
    }
  },
}

所以我有一个由 v-if="confirmed" 调节的 div#feedback,我想在确认变为真后立即滚动到它,在控制台上我收到“this.$nextTick 不是函数”错误.

有什么想法吗?

scroll vuejs3 vue-composition-api
1个回答
0
投票

需要先导入nextTick函数

import { onMounted, nextTick } from 'vue';

然后使用它

nextTick(() => {
   feedback.value.scrollIntoView({ behavior: "smooth", block: "center" });
})

await nextTick();
feedback.value.scrollIntoView({ behavior: "smooth", block: "center" });
© www.soinside.com 2019 - 2024. All rights reserved.