Building a Vue SPA with Laravel Part 2
https://laravel-news.com/building-vue-spa-laravel-part-2/
Last updated
Was this helpful?
https://laravel-news.com/building-vue-spa-laravel-part-2/
Last updated
Was this helpful?
In this tutorial, we continue Building a Vue single-page application (SPA) with Laravel by learning how to load async data from a Laravel API endpoint inside a Vue component. We will also look at error handling when an API response returns an error and how to respond in the interface.
If you didn’t read , we covered wiring up a Vue single page application (SPA) with Vue Router and a Laravel backend. If you want to follow along, you should go read through Part One first!
To keep the server-side data simple, our API will use fake data. In Part 3, we will convert the API to a controller with test data coming from a database.
Vue SPA applications are stateless, meaning that we make API calls to the Laravel router with our routes defined in routes/api.php
. The API routes don’t use session state, meaning our application is truly stateless on the backend.
In our example, let’s say we wanted to get a list of users that we can use to demonstrate making an asynchronous request to the backend from our Vue app:
Our temporary route is using to create a collection of Eloquent models that are not yet persisted to the database. We use make()
method, which doesn’t attempt to insert the test data into the database, instead it returns a collection of new App\User
instances that haven’t been persisted yet.
Defining a route in the routes/api.php
file means our requests have a prefix of /api
, because of the prefix defined in the app’s RouteServiceProvider
class:
Our user resource is GET /api/users
and an example response might look like this:
If you followed along in Part 1, we built a couple of routes in the resources/assets/js/app.js
file to demonstrate navigating around the SPA. Any time we want to add a new route, we create new object in the routes
array which define the path, name, and component of each route. The last route is our new /users
route:
The router defines a route using the UsersIndex
component; here’s what the file (located at resources/assets/js/views/UsersIndex.vue
) looks like:
In this component, we are fetching asynchronous data during the component created hook. We define a fechData()
method which resets the error and users properties to null
, sets loading
to true.
Here’s what the console data will look like if you load up /users
in the application (the client-side page, not the API):
Object destructuring is an efficient way of taking only the props needed for an object and is more concise/readable.
We have the route and component for /users
, let’s hook up a navigation link in the main App
component and then set the user data from the users
response:
In resources/assets/js/views/App.vue
, add a link using the route name we have the users index:
Next, let’s update the UsersIndex.vue
file to set the user data:
Now if you refresh the page, you should see something like the following:
Our component should work as expected most of the time, but we aren’t handling API errors yet. Let’s add a simulated server error to the API endpoint:
We use rand()
to abort the request if the number is less than three. If you refresh the page a couple of times you should see the “Loading…”, and if you inspect the developer tools you’ll see an uncaught exception from the Axios request:
We can handle a failed request by chaining a catch()
callback on the Axios promise:
We set the loading data property to false
and use the error exception to try to set a message
key from the response. The message falls back to the exception.message
property.
For good measure, let’s give the user a “Try Again” button on this condition within the UsersIndex.vue
template, which simply calls our fetchData
method to refresh the users
property:
Now if things fail, the UI should look like this:
In this short article, we added a new route to list out some fake users from a stateless Laravel API endpoint. We used an “after navigation” data fetching strategy to get the data. Or to put it another way, we requested the data from the API when the component is created.
We will also convert the API to use a database table with seed data so we can go over navigating to an individual user which covers using router params.
If you are new to Vue, there might be a couple of unfamiliar concepts here. I recommend reading the Vue documentation and get familiar with the Vue lifecycle hooks (created, mounted, etc.).
The final line in the fetchData()
method uses the library to make the HTTP request to our Laravel API. Axios is a promise-based HTTP client, which we use to chain the then()
callback where we log the response and will eventually set it to the users
data property.
Another thing I would like you to pay attention to is the going on here:
In we will look at using a callback in the Vue Router to fetch data before navigating to a component to show you how to fetch data before rendering a router view.
Now, onward to of Building a Vue SPA with Laravel!