vue3 获取循环的div的总宽度

发布时间 2024-01-12 11:19:22作者: 蓝色精灵jah

要获取循环的 <div> 元素的总宽度,您可以使用 Vue 3 中的 ref$refs

在模板中,使用 v-for 循环生成多个 <div> 元素,并为父元素和每个子元素添加 ref 属性。例如:

<template>
  <div ref="parentDiv">
    <div v-for="item in items" :key="item.id" ref="divItem" class="item">{{ item.name }}</div>
  </div>
</template>

 

  然后,在组件的 JavaScript 部分,使用 $refs 来访问 ref 引用的元素,并计算所有 <div> 元素的总宽度。例如:

<script>
import { ref, onMounted, nextTick } from 'vue';

export default {
  setup() {
    const divItem = ref(null); // 创建一个引用
    onMounted(() => {
        let totalWidth = 0;
        const divElements = divItem.value; // 获取所有 <div> 元素的引用
          setTimeout(() => {
           divElements.forEach((element) => {
              totalWidth += element.$el.offsetWidth; // 累加每个 <div> 元素的宽度 offsetWidth 返回元素的宽度(包括元素宽度、内边距和边框,不包括外边距)

           });
        }, 200);
        console.log('总宽度:', totalWidth);
   
    });

    return {
      divItem
    };
  }
};
</script>