In Nuxt, we can create "plugins" or global functions by injecting them into the three following items:
- The Vue instance (on the client side):
// plugins/<function-name>.js
import Vue from 'vue'
Vue.prototype.$<function-name> = () => {
//...
}
- The Nuxt context (on the server side):
// plugins/<function-name>.js
export default (context, inject) => {
context.app.$<function-name> = () => {
//...
}
}
- Both the Vue instance and the Nuxt context:
// plugins/<function-name>.js
export default (context, inject) => {
inject('<function-name>', () => {
//...
})
}
Using the preceding formats, you can write global functions easily for your app. In the coming sections, we will guide you through some example functions. So let's get started.