How to break the loop using the v-if directive in VueJS?

Hi Friends đź‘‹,

Welcome To SortoutCode! ❤️

To break the loop in Vue. we are going to use the v-if with the index of the array in Vue.

Today, I am going to show you How do you break loop using the v-if directive in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Create FirstComponent.vue and import it into App.js
  • Using the v-if with array index

This article will guide you to how do I break loop using the v-if directive in vueJS.

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?

Create FirstComponent.vue and import it into App.js

Create the new component in the src/components/ components folder. the component name is FirstComponent.vue and imported into the App.js file:

App.js

<template>
  <div id="app">
    <FirstComponent />
  </div>
</template>

<script>
import FirstComponent from "./components/FirstComponent.vue";
export default {
  name: "App",
  components: {
    FirstComponent,
  },
};
</script>

Using the v-if with array index

We are going to call API through the fetch method and we are using the get method. we are going to save the API response in the users data variable.

To break the loop we are going to use directive v-if is used to conditionally render a block. In the API response result is ten lists. But using the v-if directive with an index of the array we print the five blocks. Let’s see the code example:

FirstComponent.js

<template>
  <div id="app">
    <div style="display: flex; flex-wrap: wrap">
      <div v-for="(item,index) in listItems" :key="item.id" v-if="index <= 5" class="card">
        <div class="card-body">
          <h6>
            <b>Name: {{ item.name }}</b>
          </h6>
          <p>Email Id: {{ item.email }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "FirstComponent",
  data() {
    return {
      listItems: [],
    };
  },
  methods: {
    async getData() {
      const res = await fetch("https://jsonplaceholder.typicode.com/users");
      this.listItems = await res.json();
    },
  },
  mounted() {
    this.getData();
  },
};
</script>

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

For now, let’s check the output.

Break Loop

All the best 👍.

Follow me on Twitter