The global helper function is a function that is shared across all components and can access from every component. It is often used to share a common utility that does not belong to any particular component. In this article we will create function call getUniqueArray and call it in component as a example.
Create your global helper function
In your src/helpers/helper.js write any global function
export default {
getUniqueArray(arr) {
return [...new Set(arr)];
}
}
Register your global function
In main.js
import Vue from 'vue'
import App from './App.vue'
import helpers from './helpers/helper'
Vue.config.productionTip = false
const plugins = {
install() {
Vue.helpers = helpers;
Vue.prototype.$helpers = helpers;
}
}
Vue.use(plugins);
new Vue({
render: h => h(App),
}).$mount('#app')
Using global helper function
After register global helper function you can access function by this.$helpers.functionName() or Vue.helpers.functionName()
<template>
<div>
{{ uniqueArray }}
</div>
</template>
<script>
export default {
data() {
return {
duplicate_array: [1, 1, 2, 2, 3, 4]
}
},
computed: {
uniqueArray() {
return this.$helpers.getUniqueArray(this.duplicate_array)
}
}
}
</script>