How to define and render an array of data in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

Today, I am going to show you How do you define and render an array of data in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Define array in data
  • Render the Array

This article will guide you to how do I define an array and how to render the array in vueJS.

Step 1: Setup the Vue (Optional)

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Step 2: Define array in data function

First, I am going to create a component with the name FirstComponent.vue and register it. Data is the private memory of each component where you can store any variables you need.

First of all, what is data function in Vue?

Data is used to define properties in a particular component. In a single-file component, data is a function that returns a set of properties that have been defined in the function.

I am going to add a items array property to our FirstComponent.vue component, I can do it using data as shown in the script:

FirstComponent.vue

<template>
    <div>
        ....
    </div>
</template>

<script>
export default {
    name: 'FirstComponent',
    data() {
        return{
            items: [{ id:1 , message: 'Hi Friends' }, { id:2 , message: 'Welcome To SortoutCode!' }]
        }
    }
}
</script>

Step 3: Render the array

we can render a list of items based on our items array using the v-for. The v-for directive requires a special syntax in the form of item in items, where items are the source data array and item is an alias for the array element being iterated on:

<template>
    <div>
        <div v-for="item in items" :key="item.id">
            <h2>{{item.message}}</h2>
        </div>
    </div>
</template>

<script>
export default {
  name: 'FirstComponent',
  data() {
      return{
          items: [{ id:1 , message: 'Hi Friends' }, { id:2 , message: 'Welcome To SortoutCode!' }]
      }
  }
}
</script>

For now, let’s check the output.

Render Array

All the best 👍.

Follow me on Twitter