In this example, we will create a function for multiplying two numbers, for example, 2 * 3 = 6. We will inject this function into both the Vue instances and the Nuxt context in the following steps:
- Create a .js file and use the inject function to encapsulate your function:
// plugins/combined-injections/multiply.js
export default ({ app }, inject) => {
inject('multiply', (x, y) => x y)
}
Note that $ is prefixed automatically to your function, so you don't have to worry about adding it to your function.
- Add the function file path to the plugins property in the Nuxt config file:
// nuxt.config.js
export default {
plugins: ['~/plugins/combined-injections/multiply']
}
- Use the function on any page you like where you have access to context and this (the Vue instance), such as the following, for example:
// pages...