In this example, we will create a function for summing up two numbers, for example, 1 + 2 = 3. We will inject this function into the Vue instance with the following steps:
- Create a .js file, import vue, and attach the function to vue.prototype in the /plugins/ directory:
// plugins/vue-injections/sum.js
import Vue from 'vue'
Vue.prototype.$sum = (x, y) => x + y
- Add the function file path to the plugins property in the Nuxt config file:
// nuxt.config.js
export default {
plugins: ['~/plugins/vue-injections/sum']
}
- Use the function anywhere you like, such as the following, for example:
// pages/vue-injections.vue
<p>{{ this.$sum(1, 2) }}</p>
<p>{{ sum }}</p>
export default {
data () {
return {
sum: this.$sum(2, 3)
}
}
}
- Run the page on the browser and you should get the following output on the screen (even when you refresh the page):
3
5