How to encapsulate the common functionality in a Vuejs project? Best Practice

血红的双手。 提交于 2019-12-03 02:58:53

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!