【问题标题】:Vue3 Composite API window.scrollTo element of ref ArrayVue3 Composite API window.scrollTo 元素的 ref Array
【发布时间】:2022-11-10 22:13:22
【问题描述】:

有人知道如何使用复合 API 在 Vue3 中获取元素的 offsetTop 吗?喜欢这个版本的 Vue2?

goto(refName) { 
  var element = this.$refs[refName];
  var top = element.offsetTop;     
  window.scrollTo(0, top);
}

我在我的设置():

const accordions = ref([]);
...
<Disclosure
    v-slot="{ open }"
    v-for="(region, index) of data"
    :key="index"
    :ref="(el) => pushToRef(el, index)"
  >...</Disclosure>

function pushToRef(el, index) {
  accordions[index] = el;
}

它由 v-for 的元素填充。稍后我可以将代理从阵列中取出。但不是偏移量:

const element = accordions[region]; 
console.log("Region: " + region); //got the name 
console.log("Element: ", element); // Proxy of element 
const top = element.offsetTop; // UNDEFINED ???
console.log("OffsetTop: " + top); // !!! Undefined 
window.scrollTo({ top: top, left: 0, behavior: "smooth", });

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    我相信您的代码在安装组件之前正在运行。 尝试将其包装在 onMounted

    import { onMounted } from 'vue'
    
    onMounted(() => {
      const element = accordions[region];
      const top = element.offsetTop;
      console.log("OffsetTop: " + top);
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2023-02-03
      • 2022-06-14
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多