Vue dynamically added :ref in v-for are not shown in this.$refs

1.1k Views Asked by At

I'm new to vue.js, and I have a vue.js component that basically shows numbers from a data array when the button "Add elements" is clicked, the code is the following:

<template>
  <div>
    <button @click="updateCounter">Add elements</button>
    <div
      v-for="number in numsArray"
      :key="number"
      :ref="`${number}`"
    >
      <div>
        <p>{{ number }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { SocketUpdate as socketUp } from "./components/Data";

export default {
  name: "App",
  data() {
    return {
      numsArray: [],
      counter: 0,
    };
  },
  mounted() {
    console.log("REFS when mounted::", this.$refs);
  },
  beforeUpdate() {
    console.log("REFS before updated::", this.$refs);

  },
  updated() {
    console.log("REFS updated::", this.$refs);
  },
  methods: {
    updateCounter() {
      this.counter++;
      const copyOfArray = [...this.numsArray];
      copyOfArray.push(this.counter);
      this.numsArray = copyOfArray;
      console.log(this.numsArray);
    }
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

However, 1. when the button is clicked and new elements are added to the numsArray and displayed in the v-for div, the :ref="${number}" is never associated to the respective element, because when trying to print the this.$refs array in the mounted, updated or beforeUpdated hooks; that array empty (no refs) which means that the elements are created in the DOM, those numbers are visible, but the refs related to them are never created nor added to the this.$refs array. And 2. The console.log("REFS...", this.$refs); is only shown in the beforeUpdate when the button is clicked, and once in the mounted, so hows possible that the component passed through the beforeUpdate and not in the updated, if the data elements (numsArray in this case) were updated, do you know how exactly is the updated hook is invoked?

Thanks you!

0

There are 0 best solutions below