How did I use the Service Pattern in NuxtJS?

Tram Ho


In the process of making VueJS NuxtJS or even Laravel, I often apply patterns like Service or Repository. I’ve also experienced Angular, and actually it supports these patterns quite well and in a framework. With VueJS or Nuxt, the devs will need to have experience and build by hand. This article I want to share about how to use the Service pattern in NuxtJS that I usually do to serve the business logic processing.

Why should I use it?

  • The first is that I will independently handle the business logic, the code is both beautiful and clear and easy to maintain.
  • Factory pattern application is smoother, if possible I will have the opportunity to write about this guy.
  • Since it’s independent … it’s easier to reuse.
  • Writing tests is simpler.

Boil down, I saw when I maintaince projects and there is no pattern as on the whole encounter one problem Instead I have to fix one file, I had to fix dozens of files

Implemented by example

  • In this example, I will take a Product instance as a demo and in the project will use axios to serve the API call (or possibly add VueX).
  • First of all, in the plugins directory, I will have a file like the following

  • In Vue component I can use it as follows

  • Or when used with Vuex

Actual case implementation

  • Ok above is an example of implementing a service, in the case of the actual case we can refer to the implementation as follows:

  • In AxiosConfig.js will proceed to return an instance of axios

  • In each service we will proceed to inject clients

  • And now it’s time to register the Services into the services/Index.js file

… And then the call in asyncData or MapGetters bla bla v …. v =)))


  • Above are the ways I usually do, if you have other ways, please comment below the article for everyone to study and share.
  • NOTE: There will be many friends after reading: Why does it look like the Repository Pattern ?? Actually, I only have an example of calling the API, but in fact I also specify that solving the business logic =)) which means later, when we only care about the API call, we can nest the Repository Pattern. That and I want to share in another article between these 2 guys!
  • Thanks for reading!
Share the news now

Source : Viblo