Back to Course |
Vue.js 3 + Laravel 11 + Vite: SPA CRUD

SweetAlert for Notifications

Now when we create a new post or edit a post, there are no notifications about successful action. In this lesson, we will add a notification using sweetalert2.

sweet alert message


To add sweetalert notifications, we will use a package avil13/vue-sweetalert2. First, let's install it.

npm install -S vue-sweetalert2

Next, we need to import styles and import/use the plugin in the main app.js file.

resources/css/app.css:

@import 'sweetalert2/dist/sweetalert2.min.css';
 
@tailwind base;
@tailwind components;
@tailwind utilities;

resources/js/app.js:

import './bootstrap';
 
import { createApp } from 'vue'
import App from './layouts/App.vue'
 
import router from './routes/index'
import VueSweetalert2 from 'vue-sweetalert2';
 
createApp(App)
.use(router)
.use(VueSweetalert2)
.mount('#app')

Now we need to call sweetalert in the posts Composable, after a successful HTTP request, with swal() method. Before doing that, we need to Vue.js inject() function.

resources/js/composables/posts.js:

import { ref } from 'vue'
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
 
export default function usePosts() {
const posts = ref({})
const post = ref({})
const router = useRouter()
const validationErrors = ref({})
const isLoading = ref(false)
const swal = inject('$swal')
 
// ...
 
const storePost = async (post) => {
if (isLoading.value) return;
 
isLoading.value = true
validationErrors.value = {}
 
let serializedPost = new FormData()
for (let item in post) {
if (post.hasOwnProperty(item)) {
serializedPost.append(item, post[item])
}
}
 
axios.post('/api/posts', serializedPost)
.then(response => {
router.push({ name: 'posts.index' })
swal({
icon: 'success',
title: 'Post saved successfully'
})
})
.catch(error => {
if (error.response?.data) {
validationErrors.value = error.response.data.errors
isLoading.value = false
}
})
}
 
const updatePost = async (post) => {
if (isLoading.value) return;
 
isLoading.value = true
validationErrors.value = {}
 
axios.put('/api/posts/' + post.id, post)
.then(response => {
router.push({ name: 'posts.index' })
swal({
icon: 'success',
title: 'Post saved successfully'
})
})
.catch(error => {
if (error.response?.data) {
validationErrors.value = error.response.data.errors
}
})
.finally(() => isLoading.value = false)
}
 
return { posts, post, getPosts, getPost, storePost, updatePost, validationErrors, isLoading }
}

After creating or editing a post now you should see a success message.

sweet alert message