当我在vue.js中使用v-for时,如何获得宽度

insrf1ej  于 2023-03-19  发布在  Vue.js
关注(0)|答案(1)|浏览(240)

我有一些数据要用v-for表示,我想得到每个元素的宽度。
在挂载中,我使用的是this.$refs.name.offsetWidth,但是它一直是0,怎么办

mounted(){
  ipcRenderer.on('getVuexMsg', (e, data) => {
    this.barrageList.push(data)
    setTimeout(()=>{
      console.log(this.$refs.text[0].offsetWidth);
    },2000)
  })
}

<div class="textArea" ref="textArea">
  <div class="text" v-for="(item,index) in barrageList" :key="index" ref="text">{{ item.content }}</div>
</div>
cvxl0en2

cvxl0en21#

您没有提供太多信息,但可能存在这样的问题:您试图在元素加载到DOM之前访问它们。
你应该用nextTick。根据它的定义-
如果你想捕捉DOM刚刚更新的时刻,那么你需要使用一个特殊的函数nextTick(callback),它在新的数据更新到达DOM之后立即执行callback。
这里有一个演示-

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>

相关问题