Home > Software engineering >  vuejs3.2 script setup - dynamic $ref
vuejs3.2 script setup - dynamic $ref

Time:01-18

I try to create a dynamic summary.

<template>
    <ul>
        <li v-for="(categorie, i) in categories" :key="i"  @click="scrollMeTo('categorie' i)">{{ categorie }}</li>
    </ul>
</div>
.....

</template>
<script setup>
import { ref } from 'vue'
let categorie0 = ref(null)
let categorie1 = ref(null)
let categorie2 = ref(null)
let categorie3 = ref(null)
let categorie4 = ref(null)
let categorie5 = ref(null)
let categorie6 = ref(null)
let categorie7 = ref(null)
....
function scrollMeTo(refName) {
  [refName].value.scrollIntoView({ behavior: "smooth" });
}
...
</script>

Prior to 3.2 and the script setup, I used this function to scroll the id, but I don't understand how I can dynamically generate a ref value.

function scrollMeTo(refName) {
  let element = this.$refs[refName];
  refName.value.scrollIntoView({ behavior: "smooth" });
}

CodePudding user response:

Check this

Starting from Vue v3.2.25 there is the Refs inside v-for.
It looks very like what you are trying to achieve.

Requires Vue v3.2.25 or above

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

const list = ref([1, 2, 3])

const itemRefs = ref([])

onMounted(() => {
  alert(itemRefs.value.map(i => i.textContent))
})
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

Vue SFC Playground

CodePudding user response:

Simply :


function scrollMeTo(refName) {
  document.getElementById('categorie'   refName).scrollIntoView({ behavior: "smooth" });
}
  • Related