Manoj Damor

Unlock the World of Coding with Coding Funda

How to Use v-for Loop in Vue.js with Laravel 11

How to Use v-for Loop in Vue.js with Laravel 11 || Manoj Damor

How to Use v-for Loop in Vue.js with Laravel 11 || Manoj Damor

In Vue.js with Laravel 11, you can use the v-for directive to loop over an array or object and dynamically render content on the frontend. This tutorial will show you how to properly create a for loop in a Vue component and integrate it into your Laravel project.


Step 1: Set up Laravel 11 with Vue.js (Optional Recap)

Make sure your Laravel 11 app is configured with Vue.js. If not, follow these steps:

  1. Install Laravel 11:
   composer create-project laravel/laravel example-app
   cd example-app
  1. Install Node dependencies:
   npm install
  1. Install Vue (if not already installed via Laravel Breeze):
   npm install vue @vitejs/plugin-vue
  1. Configure vite.config.js:
   import { defineConfig } from 'vite';
   import vue from '@vitejs/plugin-vue';
   import laravel from 'laravel-vite-plugin';

   export default defineConfig({
     plugins: [
       laravel({
         input: ['resources/css/app.css', 'resources/js/app.js'],
         refresh: true,
       }),
       vue(),
     ],
   });

Step 2: Create a Vue Component with a v-for Loop

  1. Create a Vue component to render a list using the v-for loop. resources/js/Components/UserList.vue:
   <template>
     <div>
       <h2>User List</h2>
       <ul>
         <li v-for="(user, index) in users" :key="index">
           {{ index + 1 }}. {{ user.name }} - {{ user.email }}
         </li>
       </ul>
     </div>
   </template>

   <script>
   export default {
     data() {
       return {
         users: [
           { name: 'John Doe', email: '[email protected]' },
           { name: 'Jane Smith', email: '[email protected]' },
           { name: 'Alice Johnson', email: '[email protected]' }
         ],
       };
     },
   };
   </script>

   <style scoped>
   h2 {
     color: #333;
   }
   ul {
     list-style-type: none;
     padding: 0;
   }
   li {
     margin: 5px 0;
     font-weight: bold;
   }
   </style>

Step 3: Import the Component into Your Main Vue App

  1. Update resources/js/app.js to register and mount the Vue component. resources/js/app.js:
   import { createApp } from 'vue';
   import UserList from './Components/UserList.vue';

   const app = createApp({});
   app.component('user-list', UserList);
   app.mount('#app');

Step 4: Use the Component in a Blade Template

  1. Edit the Blade view to include the Vue component. resources/views/welcome.blade.php:
   <!DOCTYPE html>
   <html lang="en">
   <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Laravel with Vue.js Loop</title>
     @vite(['resources/css/app.css', 'resources/js/app.js'])
   </head>
   <body>
     <div id="app">
       <user-list></user-list>
     </div>
   </body>
   </html>

Step 5: Run the Application

  1. Compile your assets with Vite:
   npm run dev
  1. Run the Laravel server:
   php artisan serve
  1. Open http://localhost:8000 in your browser. You should see a list of users rendered using the v-for loop.

Explanation

  • v-for Directive: Used to loop through the users array.
  <li v-for="(user, index) in users" :key="index">
    {{ index + 1 }}. {{ user.name }} - {{ user.email }}
  </li>
  • user: Each element in the users array.
  • index: The current index of the loop.
  • :key="index": A unique key to help Vue track the elements efficiently.
  • Reactivity: If the users array is updated (e.g., by fetching data from an API), the list will update automatically.

Optional: Fetch Data from Laravel API

  1. Create a Laravel route to return a list of users. routes/web.php:
   Route::get('/api/users', function () {
       return [
           ['name' => 'John Doe', 'email' => '[email protected]'],
           ['name' => 'Jane Smith', 'email' => '[email protected]'],
           ['name' => 'Alice Johnson', 'email' => '[email protected]'],
       ];
   });
  1. Update the Vue component to fetch users from the Laravel backend. UserList.vue:
   <script>
   export default {
     data() {
       return {
         users: [],
       };
     },
     mounted() {
       fetch('/api/users')
         .then(response => response.json())
         .then(data => {
           this.users = data;
         });
     },
   };
   </script>

Conclusion

You’ve successfully set up a v-for loop in Vue.js within a Laravel 11 project. This guide showed you how to:

  1. Create and register a Vue component.
  2. Use the v-for directive to loop through an array.
  3. Integrate the component into a Laravel Blade template.

Additionally, we explored how to fetch data from a Laravel route dynamically. With this setup, you can build powerful frontend features using Vue in your Laravel projects!

Check My Social Profile Links

Instagram

Youtube

Website

Linkedin

Android Application

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow by Email
fb-share-icon
Share