START

  • 番茄今天,在vue项目中,$ref取值操作发现,时而是对象时而是数组,以前没有注意到这个细节问题,今天又写了固定的ref名称,又写了for生成的ref名称。
  • 发现vue中$ref取值,静态的ref读取到的是dom对象,而for循环生成得ref,读取到的dom对象是一个数组。

详细说明

  • $ref取值操作发现,时而是对象时而是数组,以前没有注意到这个细节问题。

demo代码

<template>
  <div>
    <h1 style="text-align: center" ref="h1">固定写法的ref</h1>
    <hr />

    <div>
      <h1 v-for="(item, index) in 4" :key="index" :ref="'for_h' + index">
        第{{ index }}个,for循环生成的不同名ref
      </h1>
    </div>

    <hr />
    <div>
      <h1 v-for="(item, index) in 4" :key="index" :ref="'for2_h'">
        第{{ index }}个,for循环生成的同名ref
      </h1>
    </div>
  </div>
</template>

<script>
export default {
  mounted() {
    console.log("固定写法的ref", this.$refs.h1);
    console.log('')

    for (let index = 0; index < 4; index++) {
      console.log("for循环生成的不同名ref", this.$refs["for_h" + index]);
    }

    console.log('')

    console.log("for循环生成的同名ref", this.$refs.for2_h);
  },
};
</script>

<style>
</style>

打印效果

image-20211228000746288

官网解释

image-20211228000830362

当 v-for 用于元素或组件的时候,ref注册的引用信息将是包含 DOM 节点或组件实例的数组。也就是说通过v-for创建的每个元素不必具有不同的ref属性

END

  • 细节问题,却因为惯性思维导致卡壳卡了很久,加油
Logo

前往低代码交流专区

更多推荐