I am working with a mid size project utilizing Vuejs as the front-end. The options I am exploring to encapsulate / separate the common methods which may be used in many componen
what I prefer (someone would consider it not the best way but it is enough for me) is to create plugins.
So I have a file called vue-utils.js with the content (for example):
; (function () {
var install = function(Vue, options) {
Vue.prototype.$utils = {}
var vm = new Vue({ data: Vue.prototype.$utils });
Vue.prototype.$utils.validateEmail = function(value) {
return /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/.test(value);
}
}
if (typeof exports == 'object') {
module.exports = install;
} else if (typeof define == 'function' && define.amd) {
define([], function () { return install });
} else if (window.Vue) {
Vue.use(install);
}
})();
I define the $utils first and then I create a new Vue instance with it so I transform any property to binded, and then define another properties and methods.
Then load it in the app this way:
import VueUtils from './plugins/vue-utils.js';
Vue.use(VueUtils);
And you will be able to reach the component in the HTML like $utils and in the JS by this.$utils