In this example, we will create a function for squaring a number, for example, 5 * 5 = 25. We will inject this function into the Nuxt context via the following steps:
- Create a .js file and attach the function to context.app:
// plugins/ctx-injections/square.js
export default ({ app }, inject) => {
app.$square = (x) => x * x
}
- Add the function file path to the plugins option in the Nuxt config file:
// nuxt.config.js
export default {
plugins: ['~/plugins/ctx-injections/square']
}
- Use the function on any page you like where you have the access to the context, for example, in the asyncData method:
// pages/ctx-injections.vue
<p>{{ square }}</p>
export default {
asyncData (context) {
return {
square: context.app.$square(5)
}
}
}
- Run the page on the browser and you should get the following output on the screen (even when you refresh the page):
25
Note that asyncData...