Vue代码优化之mixins 混合器的使用

更新日期: 2019-12-14阅读: 2k标签: Mixins

使用场景

主要抽离组件共用的代码,如各个页面中分页组件的data、methods,和ui原型中统一的confirm和alert弹窗以及加载的进度条等 

 

混合器:

// mixin.js
export const page =  {
    data() {
        return {
           pageSize:20,
           currentPage: 1
           pageLength: 10,
        }
    },
 
  methods: {
    /**
     * 上一页
     */
    prevPage (page) {
      ...
    },
    /**
     * 下一页
     */
    nextPage (page) {
      ...
    }
    /**
     * 跳转到当前页
     */
    currentPage (page) {
      ...
    }
  }
}


export const ui= {
    methods: {
        async loadingData (target, callback) {
            const loading = this.$loading({
                lock: true,
                text: '处理中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.5)',
                target: target ? target : document.body,
            });
            try {
                await callback();
            } finally {
                loading.close();
            }
        },

        confirm (msg,title='提示',doConfirm, doCancel, options={}) {

          let defaultOpts ={
            type: 'warning'
          };
          let opts =  { ...defaultOpts, ...options };
          let iconClassObj = {
            'warning':'el-icon-warning-outline',
            'err':'el-icon-circle-close',
            'success':'el-icon-circle-check'
          }
          let iconColorObj = {
            'warning':'#e6a23c',
            'err':'#EE020B',
            'success':'#14B216'
          }
          const  iconClass = iconClassObj[opts.type];
          const  iconColor = iconColorObj[opts.type];
          let html =`<ihljs-subst">${iconColor}; font-size:66px;margin-top: -22px;"hljs-subst">${iconClass}"></i><br>
            <p>${title}</p><span>${msg}</span>`;
          this.$confirm(html, '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            center: true,
            cancelButtonClass:'dialog-cancel-btn',
            confirmButtonClass: 'dialog-confirm-btn'
          }).then(async () => {
            try {
              if (doConfirm) {
                await doConfirm();
              }
            }
            catch (err) {
              console.log(err);
            }
          }).catch(async () => {
            try {
              if (doCancel) {
                await doCancel();
              }
            }
            catch (err) {
              console.log(err);
            }
          });
        },

        alert (msg, title='提示', doCancel) {
            this.$alert(msg, title, {
                showConfirmButton: false,
                callback: async action => {
                    if (action == 'cancel') {
                        if (doCancel) {
                            await doCancel();
                        }
                    }
                },
            });
        },

    },
};

页面.vue

<template>
  <div class="home-model">
    <my-table :data="data"></my-table>
    <my-paging
      :page-length="pageLength"
      :page-size="pageSize"
      :current-page="currentPage"
      :total="total">
    </my-paging>
  </div>
</template>

<script>
  import page from '../mixins/mixin'
  export default {
    mixins: [page],
    data () {
      return {
        data: [],
        pageLength: 10,
        pageSize: 1,
        currentPage: 1,
        total: 20
      }
    },
    methods:{
        handleDelete(){
               this.confirm('请确认是否需要删除?','确认删除?',async () => {
                    await this.loadingData('.el-container', async () => {
                        await this.apiDeletData();
                    });
                    this.loadListData();
                });
        }
    }
  }
</script>

可以拆成三部分写:UI部分、分页数据部分、userdata的部分

链接: https://www.fly63.com/article/detial/8200

在小程序中实现 Mixins 方案

在原生开发小程序的过程中,发现有多个页面都使用了几乎完全一样的逻辑。由于小程序官方并没有提供 Mixins 这种代码复用机制,所以只能采用非常不优雅的复制粘贴的方式去“复用”代码

Vue自定义指令directive,插件的封装以及混合mixins

除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令。注意,在 Vue2.0 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。

Vue 混入

混入 (mixins) 是一种分发 Vue 组件中可复用功能的非常灵活的方式。混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。组件和混入对象含有同名选项时,这些选项将以恰当的方式混合。

Vue3 Composition API 如何替换Vue Mixins

想在你的Vue组件之间共享代码?如果你熟悉 Vue 2 则可能知道使用 mixin ,但是新的 Composition API 提供了更好的解决方案。在本文中,我们将研究mixins的缺点,并了解Composition API如何克服它们

如何在Vue 中管理 Mixins

当我们的Vue项目功能越来越多时,如果有类似的组件,可能会发现自己一次又一次地复制和粘贴相同的数据、方法和 watch。当然,我们可以将所有这些单独的文件编写为一个单独的组件

以更好的方式使用 Vue Mixins

Mixin 组件在项目中经常被用来重用一些业务逻辑,但它们有一些不确定的细微差别,这在项目开发中越来越明显。我偶尔也会遇到这种情况,它们会给代码库的重构或新功能的开发带来困难

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!