Courses

[NEW] Vue.js 3 + Laravel 11 + Vite: SPA CRUD

Vue.js version 3 introduced a new way of writing Vue components called Composition API. Since version 3.2 Vue.js release <script setup> as a new way for writing Vue components. In this lesson, we will combine <script setup> with the composables to write reusable code.


First, let's create a composable. Create a new file resources/js/composables/posts.js and put code inside.

resources/js/composables/posts.js:

import { ref } from 'vue'
 
export default function usePosts() {
const posts = ref([])
}

In this composable first, we import the ref. Ref means reference which will make posts variable reactive.

Then as in every file, we need to export default. In our case, we will export the result of the function usePosts. Such useXyz() is the default naming convention name that starts with the use.

Next, we need to add an async method for getting the posts.

resources/js/composables/posts.js:

import { ref } from 'vue'
 
export default function usePosts() {
const posts = ref([])
 
const getPosts = async () => {
axios.get('/api/posts')
.then(response => {
posts.value = response.data;
})
}
}

And all the exposed states need to be returned. Now we have posts and getPosts.

resources/js/composables/posts.js:

import { ref } from 'vue'
 
export default function usePosts() {
const posts = ref([])
 
const getPosts = async () => {
axios.get('/api/posts')
.then(response => {
posts.value = response.data;
})
}
 
return { posts, getPosts }
}

Now we need to change the Vue component. Instead of <script> use <script setup> and use just created composable.

resources/js/components/Posts/Index.vue:

<template>
// ...
</template>
 
<script setup>
import { onMounted } from "vue";
import usePosts from "../../composables/posts";
 
const { posts, getPosts } = usePosts()
onMounted(() => {
getPosts()
})
</script> // [tl! add:end]
<script>
export default {
data() {
return {
posts: []
}
},
mounted() {
this.fetchPosts()
},
methods: {
fetchPosts() {
axios.get('/api/posts')
.then(response => this.posts = response.data)
.catch(error => console.log(error))
}
}
}
</script> // [tl! remove:end]

As you can see, this way we need to write less...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 58 courses (1056 lessons, 44 h 09 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord