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...
Hello. Not sure where I should put the jsconfig.json file. Should it be at resources/js or root laravel folder? Tried both but didnt work. I'm using nvim so it might be the problem
If it isn't written in any directory then it's root. But yes I think it's your editors problem. Might need some plugin to