Vuejs项目中如何封装常用功能?最佳实践 [英] How to encapsulate the common functionality in a Vuejs project? Best Practice

查看:56
本文介绍了Vuejs项目中如何封装常用功能?最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个使用 Vuejs 作为前端的中型项目.我正在探索封装/分离可能在许多组件中使用的常用方法的选项包括混合方法和插件方法.
混合方法
我必须在要使用 mixin 方法的每个组件(文件)中编写一个导入语句.这是否会增加最终文件的大小,因为 mixin 将在多个地方导入?我可以在 mixin 方法中使用 this .

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 components include mixins approach and plugin approach.
Mixin Approach
I have to write an import statement in each of the component (file) where I want to use the mixin methods. Does this increase the final file size as the mixin will be imported at multiple places? I can use this within the mixin methods.

插件方法
我可以使用 Vue.use(MyPlugin) 全局安装插件,并在任何组件中使用插件,而无需在每个组件中导入插件.
缺点:我无法在插件方法中使用 this[field].我必须传递调用组件 vm 的实例才能使用这些方法.

Plugin Approach
I can install the plugin globally with Vue.use(MyPlugin) and use the plugin in any component without importing the plugin in each component.
Drawback: I am not able to use this[field] within the plugin methods. I have to pass the instance of the calling component vm to use such methods.

编辑 1 - 包括扩展方法
扩展方法
我可以定义一个基本组件,其中包含将在多个其他组件中使用的所有方法,然后扩展此 BaseComponent 以创建新组件.再次,我需要传入继承组件的实例,BaseComponent 中使用的 this 不是指调用/继承组件.

Edit 1 - to include Extend Approach
Extend Approach
I can define a base component with all the methods which will have use in multiple other components and then extend this BaseComponent to create new components. Here again, I need to pass in the instance of the inheriting component , this used in the BaseComponent does not refer to the calling/inheriting component.

请在下面找到类似于我使用的代码的简单示例:

Please find the trivial example of code similar to what I am using below:

    //mixin.js
    var MyMixin = {
       methods:{
          getName(){
              return this.name;
          }
       }
    };
    export default MyMixin;  


    //plugin.js
    var MyPlugin = {};

    MyPlugin.install = function(Vue, options){
        var service = {
    	getTheName(){
    	    retrun this.name;
    	},
            getTheNameVersion2(vm){  //here vm is the instance of the calling component passed as a parameter - is this proper way?
                return vm.name;
            }  
        }
    	
        Vue.prototype.$service = service;
    };

    export default MyPlugin;



    //my-component.js
    import MyMixin from './mixin';
    export default{
        template:require('./my-component-template.html'),
        mixins:[MyMixin],
        data(){
            return{
    	    name:'John Doe'
    	}
        },
        methods:{
           displayNameFromMixin(){
              console.log(this.getName()); //displays John Doe - using the mixin method.
           },
           displayNameFromPlugin(){
              console.log(this.$service.getTheName()); //error "this" references the plugin instead of the component instance
           },
           displayNameFromPluginVersion2(){
               console.log(this.$service.getTheNameVersion2(this)); //this works - passing the instance as method parameter
           }
    }   
    
    //base-component.js  
    export default{
        methods:{
            getName(vm){
                return vm.name;
            }
        }
    }   
    
//another-component.js
import BaseComponent from './base-component';
BaseComponent.extend({
    template:require('./another-component-template.html'),
    data(){
        return{
            name:'Jack Daniels';
        }
    },
    methods:{
        getNameFromBaseComponent(){
            console.log(this.getName(this)); //displays Jack Daniels - instance passed as method parameter
        }
    }
});


    //main.js

    import Vue from 'vue';
    import MyPlugin from './plugin';
    import MyComponent from './my-component';
    import AnotherComponent from './another-component';

    Vue.use(MyPlugin);

    new Vue({
        el:'body',
        components:{
            MyComponent, AnotherComponent
        }
    });

我的问题:

  1. 在每个组件中导入 mixin 文件(需要方法)这是一种有效的方法吗?
    多处导入mixin(组件文件)会重复包含mixin文件的代码,增加文件大小吗?

  1. Importing mixin file in every component (which requires the methods) is it an efficient way of doing it?
    Does importing mixin at multiple places (component files) include code of mixin file repeatedly and increase the file size?

将调用组件 vm = this 的实例作为参数传递 - 这是一个好习惯吗?是否传递组件作为方法参数的实例会导致任何效率问题吗?

Passing the instance of the calling component vm = this as a parameter - Is it a good practice? Does passing around component instances as method parameters cause any efficiency issue?

如何将this(调用/继承组件的实例)绑定到插件和/或BaseComponent中的方法,以便this引用调用/继承组件实例而不是插件/BaseComponent?

How to bind this (instance of the calling/inheriting component) to the methods within plugin and/or BaseComponent so that this refers to the calling/inheriting component instance rather than plugin/BaseComponent?

推荐答案

我更喜欢(有人会认为它不是最好的方法,但对我来说已经足够了)是创建插件.

what I prefer (someone would consider it not the best way but it is enough for me) is to create plugins.

所以我有一个名为 vue-utils.js 的文件,其中包含内容(例如):

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);
    }
})();

我首先定义 $utils,然后用它创建一个新的 Vue 实例,因此我将任何属性转换为绑定,然后定义另一个属性和方法.

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);

并且您将能够通过 this.$utils 访问 HTML 中的组件,如 $utils 和 JS 中的组件

And you will be able to reach the component in the HTML like $utils and in the JS by this.$utils

这篇关于Vuejs项目中如何封装常用功能?最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆