Vue使用extends+mixins+动态组件实现组件继承

场景

  • 基于Jeecg-Boot Vue前端框架改造,主要通过 Vue mixins 覆写一些方法逻辑(JeecgListMixin.js)
  • 所有表单的List列表展示的template视图具有共性,唯一不同的在于各自触发的modal框(列表基于antd vue table)
  • 不同的modal框通过Vue的 动态组件 解决
  • 最终,子类通过 Vue extends继承公共的父template,公共逻辑置于mixins中,而子类实际的data数据(columns)控制实际table列的展示

这里以两个具有共性的FormA、FormB为示例(无关的代码都删了),他们重构前的代码看起来的结构类似这样:

<template>
  <a-card :bordered="false">
		<!--有共性的视图-->
    
    <!--modal是没有共性的,需要换成动态组件-->
    <project-zsxmqd-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>
  
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ProjectZsxmqdModal from './modules/ProjectZsxmqdModal'
  import businessMixin from '../../mixins/businessMixin'

  export default {
    name: "ProjectZsxmqdList",
    // 两个mixins封装了公共的方法、数据
    mixins:[JeecgListMixin, businessMixin],
    components: {
      ProjectZsxmqdModal
    },
    // 表单自己维护的数据
    data () {
      return {
        description: '征收准备-征收项目确定管理页面',
        // 表头
        columns: [
          // 表单的字段
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'项目id',
            align:"center",
            dataIndex: 'projectId'
          },
          {
            title:'项目分类',
            align:"center",
            dataIndex: 'xmfl_dictText'
          },
        ],
        url: {
          list: "/project/projectZsxmqd/list",
          delete: "/project/projectZsxmqd/delete",
          deleteBatch: "/project/projectZsxmqd/deleteBatch",
          exportXlsUrl: "/project/projectZsxmqd/exportXls",
          importExcelUrl: "project/projectZsxmqd/importExcel",
          startProcess: '/act/process/extActProcess/startMutilProcess'
        },
        flowCode: 'dev_project_zsxmqd_001',
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
    },
    computed: {
    },
    methods: {
      // 表单自己的方法
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>

image-20211126143457991

开始重构

1、提取公共方法到mixins,这里JeecgListMixin.js的源码就不贴了,具体代码见Github。下面代码是我自己对有共性表单做的功能增强的businessMixin:

  • 修改了antd-table的rowSelection模式为单选
  • 增强了loadData方法,添加项目id的自动绑定
  • 增强了删除、批量删除方法,可以对关联的其他业务进行关联删除操作
  • 返回需要动态加载的modal的component名称
  • 一些其他页面判断、操作等等
import { mapGetters, mapActions } from 'vuex'
import { PROJECT_ID } from '@/store/mutation-types'
import { getAction, deleteAction } from '@/api/manage'
export default {
  mounted() {
    // 页面刷新id值不存在时跳回项目列表
    if (!this[PROJECT_ID]) {
      this.$router.push({ path: '/project' })
    }
  },
  watch: {
    selectedRowKeys: {
      immediate: true,
      deep: true,
      handler(val) {
        if (!(val && val.length)) {
          this.SetBusinessId('')
          this.SetBusinessName('')
          console.log('selectedRowKeys change none', val)
        } else {
          // 选择列表项时,发送业务关联数据
          this.SetBusinessId(val[0])
          this.SetBusinessName(this.$route.meta.title)
        }
      }
    }
  },
  computed: {
    ...mapGetters([PROJECT_ID]),
    modalName() {
      return this.$options.name.replace('List', 'Modal')
    },
    listUrl() {
      return `${this.url.list}?projectId=${this[PROJECT_ID]}`
    },
    deleteFolderUrl() {
      return {
        one: '/technical/folder/business/all/',
        batch: '/technical/folder/business/all/deleteBatch'
      }
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        type: 'radio'
      }
    }
  },
  methods: {
    ...mapActions(['SetBusinessId', 'SetBusinessName']),
    loadData(arg) {
      // console.log('businessMixin::loadData')
      if (!this.listUrl) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      getAction(this.listUrl, params).then(res => {
        if (res.success) {
          this.dataSource = res.result.records || res.result
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    batchDel() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录!');
      } else {
        var ids = '';
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ',';
        }
        const that = this;
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: async function () {
            that.loading = true
            const { success, message } = await deleteAction(that.url.deleteBatch, { ids: ids })
            if (success) {
              that.$message.success(message)
              // 删除关联目录&文件
              const { success: success2, message: message2 } = await deleteAction(that.deleteFolderUrl.batch, { ids: ids })
              !success2 && that.$message.warning(message2)
              success2 && that.$message.warning('关联目录文件删除成功')
              that.selectedRowKeys = []
              that.loadData()
            } else {
              that.$message.warning(message);
            }
            that.loading = false
          }
        });
      }
    },
    async handleDelete(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      const that = this;
      this.loading = true
      const { success, message } = await deleteAction(that.url.delete, { id })
      if (success) {
        that.$message.success(message)
        // 删除关联目录&文件
        const { success: success2, message: message2 } = await deleteAction(that.deleteFolderUrl.one + id)
        !success2 && that.$message.warning(message2)
        success2 && that.$message.warning('关联目录文件删除成功')
        that.selectedRowKeys = []
        that.loadData()
      } else {
        that.$message.warning(message)
      }
      this.loading = false
    }
  }
}

2、提取公共视图template(基于Vue Extends),这里取名:businessExtend.vue

  • 将antd-table的rowSelection由多选模式改成单选模式
  • 将固定的子modal组件替换成动态的component
  • 在这里直接引入具有共性的mixins:JeecgListMixins.js、businessMixins.js
<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24"> </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="superFieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>
      <a-button @click="batchDel" style="margin-left: 8px"><a-icon type="delete" />删除</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="rowSelection"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="record.bpmStatus === '1'">
                <a @click="startProcess(record)">发起流程</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <!-- <project-gjyjzx-modal ref="modalForm" @ok="modalFormOk"></project-gjyjzx-modal> -->
    <!-- 自动获取子组件modal名称,动态组件加载 -->
    <component :is="modalName" ref="modalForm" @ok="modalFormOk"></component>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import businessMixin from './businessMixin'
export default {
  mixins: [JeecgListMixin, mixinDevice, businessMixin]
}
</script>

3、改造FormA和FormB,继承businessExtend.vue,现在看起来将会十分简洁:

/**注意视图部分template如果存在的话,将覆盖掉businessExtend中的template**/
/**<template>这里全部都得去掉,否则将覆盖父类</template>**/
<script>
  import businessExtend from '../../mixins/businessExtend'
  import ProjectZsxmqdModal from './modules/ProjectZsxmqdModal'

  export default {
    name: "ProjectZsxmqdList",
    // 继承有共性的父类组件
    extends: businessExtend,
    components: {
      ProjectZsxmqdModal
    },
    // 表单自己维护的数据
    data () {
      return {
        description: '征收准备-征收项目确定管理页面',
        // 表头
        columns: [
          // 表单的字段
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'项目id',
            align:"center",
            dataIndex: 'projectId'
          },
          {
            title:'项目分类',
            align:"center",
            dataIndex: 'xmfl_dictText'
          },
        ],
        url: {
          list: "/project/projectZsxmqd/list",
          delete: "/project/projectZsxmqd/delete",
          deleteBatch: "/project/projectZsxmqd/deleteBatch",
          exportXlsUrl: "/project/projectZsxmqd/exportXls",
          importExcelUrl: "project/projectZsxmqd/importExcel",
          startProcess: '/act/process/extActProcess/startMutilProcess'
        },
        flowCode: 'dev_project_zsxmqd_001',
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
    },
    computed: {
    },
    methods: {
      // 表单自己的方法
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>

改造后的效果像这样:

image-20211126145806922

最后,JeecgBoot Vue前端表单组件的设计模式有许多可以学习的地方,有兴趣的小伙伴可以多翻翻人家写的源码,当然Vue的文档也得多看,每次都能有新的收获!

Logo

前往低代码交流专区

更多推荐