[Vuejs]-How can i get the width when i use v-for in vue.js

0👍

You didn’t provide much information but there could be an issue that you are trying to access the elements before they are loaded into the DOM.

You should use nextTick for that. According to its definition-

If you want to catch the moment when DOM has just been updated, then
you need to use a special function nextTick(callback). It executes
callback right after the new data updates have reached DOM.

Here is a demo-

new Vue({
  el: "#app",
  data() {
    return {
      barrageList: [{
          content: "Hello World"
        },
        {
          content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing."
        }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      console.log(this.$refs.text[1].offsetWidth);
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="textArea" ref="textArea">
    <div class="text" v-for="(item,index) in barrageList" :key="index" ref="text">{{ item.content }}</div>
  </div>
</div>

Leave a comment