How to break the loop using the slice method in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To break the loop in Vue. we are going to use the slice method in Vue.

Today, I am going to show you How do you break loop using the slice method in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Create FirstComponent.vue and import it into App.js
  • Using slice() method

This article will guide you to how do I break loop using the slice method 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 slice() method

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 using the slice method we are going to use the slice() mutation method. In API, the response result is ten lists. But using the slice method we only show the four items. Let’s see the code example:

FirstComponent.js

<template>
  <div id="app">
    <div style="display: flex; flex-wrap: wrap">
      <div v-for="item in listItems.slice(0,4)" :key="item.id" 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

Follow me on Twitter