Display Flash Message Using Vue Js in Laravel
To display flash messages using Vue.js in Laravel, you can follow these steps. This example assumes you are using Laravel as a backend API and Vue.js for the frontend.
Step 1: Install Laravel and Set Up API
If you haven't already, set up a Laravel project and create the necessary API routes and controllers for your application.
Step 2: Install Vue.js
You can use Laravel Mix to set up Vue.js easily. Install the required packages:
npm install
Step 3: Create a FlashMessage Component
Create a Vue component to handle flash messages. For example, in your resources/js/components/FlashMessage.vue
:
<template> <div v-if="message" class="flash-message"> {{ message }} </div> </template> <script> export default { data() { return { message: "", }; }, watch: { $route(to, from) { this.message = ""; }, }, methods: { showMessage(message) { this.message = message; setTimeout(() => { this.message = ""; }, 3000); }, }, }; </script> <style scoped> .flash-message { position: fixed; top: 20px; right: 20px; background-color: #28a745; color: #fff; padding: 10px; border-radius: 5px; } </style>
Step 4: Use the FlashMessage Component in Your Layout
Include the FlashMessage component in your main layout file, for example, resources/views/layouts/app.blade.php
: