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

前端 未结 1 1799
慢半拍i
慢半拍i 2021-02-06 02:40

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

相关标签:
1条回答
  • 2021-02-06 03:00

    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

    0 讨论(0)
提交回复
热议问题