How to get the first item in Vue.js array in template

in Code Write a comment

In this tutorial, you’ll learn how to render the first item of an array in Vue.js template.

There’re two ways you can use to get the first item of an array.

Example using the slice() method

You can use Array​.prototype​.slice() method inside Vue.js template.

Let’s create an array of JavaScript frameworks: Vue.js, Angular, React and Svelte.

new Vue({
  el: "#app",
  data: {
    items: ['Vue.js', 'Angular', 'React', 'Svelte']
  }
})

Now let’s render it in HTML.

<div id="app">
  <h2>Items:
  <ul>
    <li v-for="item in items">
      {{ item }}
    </li>
  </ul>
</div>

Output:

Vue.js
Angular
React
Svelte

To show the first array item use the slice(0, 1) method inside the HTML template.

<div id="app">
  <h2>Items:
  <ul>
    <li v-for="item in items.slice(0, 1)">
      {{ item }}
    </li>
  </ul>
</div>

Output:

Vue.js

As you can see it shows Vue.js, the first item from the array of JavaScript frameworks.


Hi, I'm Renat 👋

 


Example using computed property

We can achieve the same result using the Vue.js computed property.

Here’s a full example:

new Vue({
  el: "#app",
  data: {
    items: ['Vue.js', 'Angular', 'React', 'Svelte']
  },
  computed: {
    slicedArray() {
      return this.items.slice(0, 1)
    }
  }
})
<div id="app">
  <h2>Items:
  <ul>
    <li v-for="item in slicedArray">
      {{ item }}
    </li>
  </ul>
</div>

This will render:

Vue.js

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-first-item-in-array

PS: You can also check how to get the last item in Vue.js array and other Vue.js tutorials.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

3 Comments