传统项目中使用vue.js,利用混入 (mixin) 实现通用CRUD

 

混入介绍:

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。

例子:

var mixin = {
  methods: {
    foo: function () {
      console.log('foo')
    },
    conflicting: function () {
      console.log('from mixin')
    }}
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    bar: function () {
      console.log('bar')
    },
    conflicting: function () {
      console.log('from self')
    }
  }
})

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

CRUD

后台定义统一接口路径:

分页获取数据:{apiPrefix}/page/{pageNum}/{pageSize},请求方式 POST 请求入参:JSONOBJECT

保存数据:{apiPrefix}/saveData,请求方式 POST 请求入参:JSONOBJECT

根据ID获取:{apiPrefix}/getById?id=,请求方式 GET

根据ID删除:{apiPrefix}/delById/{id},请求方式 GET

批量删除:{apiPrefix}/batchDelete,请求方式 POST 请求入参:JSONARRAY

const crudMixin = {
    data: function () {
        return {
            functionName: '',
            apiPrefix: '',
            dictData: {},
            // crud
            loading: false,
            queryEntity: {},
            formData: {},
            currentPage: 1,
            pageSize: 5,
            total: 100,
            tableData: [],
            dialogVisible: false, // 弹窗显示控制
            dialogTitle: '提示', // 弹窗标题
            // 表单校验数据
            validData: {},
            clickClose: false
        }
    },
    methods: {

        queryData() {
            this.currentPage = 1;
            this.loadData();
        },

        loadData() {
            this.validData = {};
            this.loading = true;
            let that = this
            $.ajax({
                type: 'POST',
                url: that.apiPrefix + "/page/" + that.currentPage + '/' + that.pageSize,
                data: JSON.stringify(this.queryEntity),
                dataType: "json",
                contentType: "application/json",
                success: function (rsp) {
                    // 响应成功逻辑

                },
                error: function (xhr) {
                    // 接口异常逻辑
                }
            });
        },
        saveData() {
            let that = this
            $.ajax({
                type: 'POST',
                url: that.apiPrefix + "/saveData",
                data: JSON.stringify(this.formData),
                dataType: "json",
                contentType: "application/json",
                success: function (rsp) {
                    // 保持成功逻辑
                },
                error: function (xhr) {
                    // 接口异常逻辑
                }
            });
        },
        // 分页
        handleSizeChange(val) {
            this.pageSize = val;
            this.loadData();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.loadData();
        },
        handleData(id, type) {
            if ("add" === type) {
                this.dialogTitle = '新增' + this.functionName;
            } else {
                this.dialogTitle = '编辑' + this.functionName;
            }
            this.dialogVisible = true;
            let that = this;
            $.get(that.apiPrefix + "/getById?id=" + id, function (rsp) {
                that.formData = rsp.data;
            })
        },
        handleDelete(row) {
            let that = this;
            this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.get(that.apiPrefix + "/delById/" + row.id, function (rsp) {
                    // 请求成功逻辑
                })
            }).catch((xhr) => {
                // 接口异常逻辑
            });

        },

        // 处理表格多选
        handleSelectionChange(selection) {
            this.selectedRows = selection;
        },

        // 批量删除
        handleBatchDelete() {
            if (!this.selectedRows || this.selectedRows.length === 0) {
                this.$message.warning('请选择要删除的数据');
                return;
            }

            this.$confirm('确认要删除选中的 ' + this.selectedRows.length + ' 条数据吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids = this.selectedRows.map(item => item.id);
                http.post(this.apiPrefix + '/batchDelete', ids)
                    // 请求成功逻辑
            }).catch(() => {
                // 接口异常逻辑
                this.$message.info('服务异常');
            });
        },
    },
    mounted() {
        this.loadData();
    }
};

 

使用:

<script>
    new Vue({
        el: '#app',
        mixins: [crudMixin],
        data: function () {
            return {
                functionName: "商品分类",
                apiPrefix: "/admin/goodsType",
                queryEntity: {
                },
            }
        },
        methods: {
        
        },
        watch: {
          // 监听弹窗状态,确保编辑器正确初始化
          
    	 },
    })
</script>