Home » vue » How to get all list items using ref?

How to get all list items using ref?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I know how to get parent ul by just doing this.$refs.listOfItems but not sure how to get all the lis in ul list.

I also know the JS way of doing it document.getElementById("listOfItems").getElementsByTagName("li"); but as mentioned above I am looking for helpers offered by Vue.js like this.$refs

<template>
  <ul id="listOfItems" ref="listOfItems">
    <li v-for="item in items">{{ item.name }}</li>
  </ul>
</template>

<script>
  export default {
    mounted: {
      let ul = this.$refs.listOfItems
      let lis =  // HOW TO GET ALL LIs using `this.$refs.listOfItems`
    }
  }
</script>
Answers:

I think you meant to put the v-for on the <li> instead of the <ul>. If you put a ref on an element that is repeated with v-for, then it will be an array of the items.

<ul>
  <li v-for="item in items" ref="items">{{ item.name }}</li>
</ul>
this.$refs.items[0];  // The first <li>