In previous chapters, you learned that we can create a plugin with the inject method and install the plugin through the Nuxt config file. Besides using the inject method, it is worth knowing that we can also inject a plugin directly into the Nuxt context. Let's take a look at how to do this:
- Create an axios-typicode.js file in the /plugins/ directory, import the vanilla axios, and create the instance, as follows:
// plugins/axios-typicode.js
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
})
export default (ctx, inject) => {
ctx.$axiosTypicode = instance
inject('axiosTypicode', instance)
}
As you can see, after creating the axios instance, we inject the plugin through the Nuxt context (ctx), use the inject method, and then export it.
- Install this plugin in the Nuxt config file:
// nuxt.config.js
export default {
plugins...