Vue.js and REST API coding quick tips

Last updated

Antonio Ufano avatar

Antonio Ufano

I've spent the last couple of weeks building web applications using Laravel APIs in the back end and Vue.js in the front end. I really like this combination as with Laravel you can build APIs very quick, it manages user authentication from scratch and generates oauth tokens for API requests with Passport, which is included by default.

On the other side I've wanted to learn a JavaScript framework to build SPAs and after reading the differences between Angular, React and Vue, I decided to use the last one. The documentation is great, it's very light and the performance is awesome. Also the Chrome/Firefox extension makes it pretty nice to debug you apps.

I've created a small application that contains examples of most of the tips I'm detailing below. Feel free to clone it and use it as a reference.

Installing and compiling Vue.js

  • If you want to build a standalone Vue front end, you can just create it importing the Vue library from a CDN as detailed in the documentation:
<script src="https://cdn.jsdelivr.net/npm/vue">script>
  • Laravel comes with Vue.js as a dependency so if you want to start using it in your project you'll have to install Node and npm first and then you just have to run $npm install in the project folder to download it. In addition it comes with an example component that you can import in any of your views.

  • You have to compile the code after every change, as Vue compiles everything to plain javascript. You can use "$npm run dev" to compile it once or you can run the command "$npm run watch" so it automatically complies every time a file is modified.

Tips to build APIs

  • Do not use GET request to alter data.

  • When building your API, if a method creates (POST request) or modifies (PUT request) a resource, always send it in the response so the front end can handle it.

  • Use different controllers for API and Web requests. Even different ones for different API versions.

  • Even if you define your Laravel API routes as using PUT or DELETE HTTP verbs, to test them in Postman you have to use POST and include a _method parameter in the request with the HTTP verb you defined in your routes.

  • When your resources (models) are related, use resource related routes to access to them. For example if we want to retrieve the list of Comments of a Post our route should be /posts/{post_id}/comments.

  • Always return the data transformed and ready to use for your front end. For example if you have a date in your back end and in the front you want do display the difference of days with the current day, it's a good idea to calculate that in the back end.

  • Return HTTP status codes so you easily handle the response of the requests. The most common ones are 200 (successful request), 201 (resource created), 204 (resource deleted), 400 (bad request), 401( unauthorised), 404 (not found) and 500 (internal error).

Tips to build a Vue.js front end

I highly recommend the Vue Mastery video tutorials as they explain all the basics about Vue and the different directives with very easy to understand examples. You can also download the cheat sheet with all the essential notes in just a couple pages.

  • Your Vue front end can interact with an API using axios, a promise based JavaScript library. Find below some examples methods to retrieve and send data:
getTasks() {

    axios.get('/api/tasks')

        .then(response => this.tasks = response.data)

        .catch(error => {});

},

postTask() {

  axios.post('/api/tasks', this.newtask )

      .then(response => this.tasks.push(response.data))

      .then(console.log('Task sucessfully saved!'))

      .catch(error => {});

}

  • Vue components and their logic/directives are data binded so first thing to do is to define the variables you need in data{} or props{}. Then create the basics of the template and using the data{} and props{} add the necessary directives for conditional rendering, event handling and methods (for example API requests). Regarding the methods, I usually create dummy ones that just print a text or the values of some variables in the console before adding more complex logic.

  • When displaying a list of items (for example a list of tasks) I usually consider creating two separated ones: a list-items component and an item component. Then in the list-items component I create all methods required to manage the data and use a v-for directive to create as many item components as needed.

  • A component can share data with a child via props[] and the child can emit events to interact with the parent:

  • Communication

Image from Laracasts

  • When creating or modifying data via API requests, always save the response back to your data (your API should return modified/new objects as mentioned earlier) to avoid doing an additional API request to refresh the data{}.

  • It's not a good practice to modify props{} values (Vue extension will display a warning if you do so). When facing this scenario, emit an event, capture it in the parent component and modify the data then. The child component (which access the data via props{}) will automatically pick the new data values.

I'll try to keep this post updated with more tips.

Happy coding!

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Oh! and don't forget to follow me on Twitter where I share tons of dev tips 🤙

Other articles that might help you

my projects

Apart from writing articles in this blog, I spent most of my time working on my personal projects.

lifeboard.app logo

theLIFEBOARD.app

theLIFEBOARD is a weekly planner that helps people achieve their goals, create new habits and avoid burnout. It encourages you to plan and review each week so you can easily identify ways to improve your productivity while keeping track of your progress.

Sign up
soliditytips.com logo

SolidityTips.com

I'm very interested in blockchain, smart contracts and all the possiblilities chains like Ethereum can bring to the web. SolidityTips is a blog in which I share everything I learn about Solidity and Web3 development.

Check it out if you want to learn Solidity
quicktalks.io logo

Quicktalks.io

Quicktalks is a place where indie hackers, makers, creators and entrepreneurs share their knowledge, ideas, lessons learned, failures and tactics they use to build successfull online products and businesses. It'll contain recorded short interviews with indie makers.

Message me to be part of it