VUE传统方式开发下的 Element UI + RequreJS单页应用

后端开发人员很少接触node.js,因为要花很多精力去学,不易上手,这里用RequreJS来简单代替WebPack吧,用它来记录JS库的路径,依赖关系,按需动态加载,这样一个前端工程化的架构也就初步形成了。

首先说一说RequreJS的基本用法,使用RequreJS需要两个文件,一个是JS库本身,一个是它的配置文件,下图我是这样放置的

VUE传统方式开发下的 Element UI + RequreJS单页应用_第1张图片

RequreJS的配置文件我就叫 require.data.main.js了,里面记录了JS库的路径和依赖关系,这些路径全都是相对于require.data.main.js这个文件的相对路径,这点一定要注意,例如下图

require.config({
    map: {
        '*': {
            css: '../lib/css'
        }
    },
    paths: {
        /*公用组件***************************************************************************************/
        LinqJS: ['linq.min'],
        PhotoUpload: ['photoUpload'],
        SelectPage: ['v-selectpage'],
        VueExtend: ['vue-extend-func'],
        /*公用业务逻辑组件*******************************************************************************/
        //组织机构分配用户
        OrganizationUserComponent: ['../Pages/Users/OrganizationUserComponent'],
        //选择用户组件
        UserSelectComponent: ['../Pages/Users/UserSelectComponent'],
        //客户订单转为生产订单
        OrderTransferProduct: ['../Pages/Orders/OrderTransferProduct'],
        //选择油罐
        ChooseOiltank: ['../Pages/Orders/ChooseOilTank'], 
        //订单配方流程图
        OrderRecipeFlow: ['../Pages/Orders/OrderRecipeFlow'], 
        //生产订单模板
        OrderProductTemplate: ['../Pages/Orders/OrderProductTemplate'], 
    },
    shim: {
        PhotoUpload: ['css!photoUpload.css'],
        SelectPage: ['css!v-selectpage.css'],
        OrderTransferProduct: {
            deps: ["SelectPage", "ChooseOiltank","OrderRecipeFlow"],
        },
        ChooseOiltank: {
            deps: ["SelectPage"],
        },
        OrderProductTemplate: {
            deps: ["LinqJS"],
        },
    }
});

注意这一行 css: '../lib/css',这里使用了一个RequreJS的插件,用来动态加载css的库,shim 下则记录了JS库依赖的其他库或css文件,上面的路径上JS文件全都不用写.js文件后缀名,写了反而会报404找不到的错误,RequreJS配置文件的用法比较简单,这里就不写那么详细了

VUE传统方式开发下的 Element UI + RequreJS单页应用_第2张图片

在使用RequreJS库的地方要这样引用 

跟一般JS文件引用不同的是 data-main 上面要写上配置文件的路径,这样一来就可以使用RequreJS来按需动态加载JS文件了

比如说,有一个导航树,点击以后动态的加载一个Vue组件可以这么写,

            require(['UserSelectComponent'], function () {
                that.userSelectShow = true;
            });

上面的 UserSelectComponent 是在 require.data.main.js 这个RequreJS配置文件中早就注册好的组件别名。所以把上面的这一套连起来看,也就知道怎么用了,Vue组件的用法这里不详细写了,下面写一下如何动态的加载组件,下例是一个典型的左边导航树,右边浏览页的结构,传统的做法是iframe里面套上不同的页面,缺点不用我多说,加载慢,跨页调用等等,很多不好的地方。

VUE传统方式开发下的 Element UI + RequreJS单页应用_第3张图片

上图每个Tab页都是个动态加载出来的Vue组件,所有的东西都是在同一个页面,没有跳转,加载速度和体验比iframe不止好一点点,下面给出主要代码,后端接口的代码就不贴了,因为没什么意义

导航树的界面

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

最重要的是这个部分

                        
                            
                        

 component : is = xxx 这是Vue里面动态加载组件的标记,keep-alive 则表示缓存这个组件,具体用法可以百度了,这里篇幅有限,不展开写了

const store = new Vuex.Store({
    state: {
        showUserSelect: false
    },
})
var minWidth = 0;
var app;
Vue.prototype.$ELEMENT.size = "small";
$(document).ready(function () {
    app = new Vue({
        el: "#app",
        directives: {
            resize: Vueresize, //注册v-resize指令
        },
        store,    //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
        data: {
            editableTabsValue: '',
            editableTabs: [],
            showUserSelect: false,
            collapseIcon: 'el-icon-s-fold',
            isCollapse: true,
            treeData: [],
            treeSelectNode: null,
            filterText: '',
            props: {
                label: 'label',
                children: 'children'
            },
            menuVisible: false,
        },
        watch: {
            isCollapse(val) {
                app.collapseIcon = val == true ? 'el-icon-s-fold' : 'el-icon-s-unfold';
            },
            filterText(val) {
                app.$refs.tree.filter(val);
            },
            editableTabsValue(val) {
                let tabs = this.editableTabs;
                var activeInde = 0;
                let activeName = val;
                tabs.forEach((tab, index) => {
                    if (tab.name === activeName) {
                        activeInde = index;
                    }
                });
                this.$nextTick(() => {
                    var elMain = $('.el-main')[0];
                    if (elMain.scrollWidth > elMain.clientWidth || elMain.scrollHeight > elMain.clientHeight) {
                        app.$refs.tabsRef[activeInde].$el.style.width = elMain.clientWidth - 30 + "px";
                    }
                });
            }
        },
        mounted() {
            this.$nextTick(() => {
                app.loadTreeData();
            });
        },
        methods: {
            onSelectUser() {
                require(['UserSelectComponent'], function () {
                    app.$store.state.showUserSelect = true;
                });
            },
            loadTreeData() {
                let loading = app.$loading();
                $.ajax({
                    type: "POST",
                    url: "/Organization/LoadTree",
                    success: function (data) {
                        if (data.Success) {
                            app.treeData = data.Data;
                        }
                        loading.close();
                    }, error() {
                        app.$message.error("请求失败!");
                        loading.close();
                    }
                });
            },
            rightClick(event, data, node, self) {
                this.menuVisible = false
                if (node) { app.treeSelectNode = node }
                var menu = document.querySelector('#menu')
                menu.style.left = event.clientX + 'px'
                menu.style.top = event.clientY - 10 + 'px'
                document.addEventListener('click', this.foo)
                this.menuVisible = true
            },
            foo() { // 取消鼠标监听事件 菜单栏
                this.menuVisible = false
                document.removeEventListener('click', this.foo) // 要及时关掉监听
            },
            collapseStatus() {
                this.collapseBtnClick = this.isCollapse;
                this.isCollapse = !this.isCollapse;

                let tabs = this.editableTabs;
                var activeInde = 0;
                let activeName = this.editableTabsValue;
                tabs.forEach((tab, index) => {
                    if (tab.name === activeName) {
                        activeInde = index;
                    }
                });
                this.$nextTick(() => {
                    var elMain = $('.el-main')[0];
                    if (elMain.scrollWidth > elMain.clientWidth || elMain.scrollHeight > elMain.clientHeight) {
                        app.$refs.tabsRef[activeInde].$el.style.width = elMain.clientWidth - 30 + "px";
                    }
                });
            },
            //节点过滤
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            //添加节点
            onAddNode() {
                app.$prompt('请输入组织机构名称', '添加组织机构', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: ''
                }).then(({ value }) => {
                    if (value.length == 0) {
                        return;
                    }
                    var parent_id = 0;
                    if (app.treeSelectNode &&
                        app.treeSelectNode.data &&
                        app.treeSelectNode.data.id) {
                        parent_id = app.treeSelectNode.data.id
                    }
                    var cloneObj = {
                        "id": "",
                        "label": value,
                        "name": value,
                        "parent_id": parent_id,
                    };
                    $.ajax({
                        type: "POST",
                        url: "/Organization/NewModel",
                        data: JSON.stringify(cloneObj),
                        success: function (data) {
                            if (data.Success) {
                                var newChild = data.Data;
                                if (!newChild.children) {
                                    app.$set(newChild, 'children', []);
                                }
                                app.$nextTick(() => {
                                    if (app.treeSelectNode &&
                                        app.treeSelectNode.data &&
                                        !app.treeSelectNode.data.children) {
                                        app.$set(app.treeSelectNode.data, 'children', []);
                                    }
                                    if (app.treeData.length == 0) {
                                        app.treeData.push(cloneObj);
                                    }
                                    else {
                                        cloneObj.id = newChild.id;
                                        app.treeSelectNode.data.children.push(cloneObj);
                                    }
                                    app.$message({
                                        type: 'success',
                                        message: '创建成功!'
                                    });
                                });
                            }
                            else
                                app.$message.error("创建失败!");
                        }, error() {
                            app.$message.error("创建失败!");
                        }
                    });
                });
            },
            //删除节点
            onRemoveNode() {
                if (app.treeSelectNode.data.children &&
                    app.treeSelectNode.data.children.length &&
                    app.treeSelectNode.data.children.length > 0) {
                    app.$message.error("请先删除所有子节点!");
                    return;
                }
                app.$confirm("是否删除此节点?", "提示", {
                    confirmButtonText: "确认",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    var ids = [];
                    ids.push(app.treeSelectNode.data.id);
                    $.ajax({
                        type: "POST",
                        url: "/Organization/DeleteModel",
                        data: JSON.stringify({ ids: ids }),
                        success: function (data) {
                            if (data.Success) {
                                var treeNode = app.treeSelectNode;
                                var treeData = app.treeSelectNode.data;
                                const parent = treeNode.parent;
                                const children = parent.data.children || parent.data;
                                const index = children.findIndex(d => d.id === treeData.id);
                                children.splice(index, 1);
                                app.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                            }
                        }, error() {
                            app.$message.error("重命名失败!");
                        }
                    });
                }).catch(() => {
                    return false;
                })
            },
            //重命名
            onRenameNode() {
                app.$prompt('请输入名称', '重命名', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: Object.assign(app.treeSelectNode.data.label)
                }).then(({ value }) => {
                    if (value.length == 0) {
                        return;
                    }
                    var cloneObj = Object.assign(app.treeSelectNode.data);
                    cloneObj.label = value;
                    cloneObj.name = value;
                    $.ajax({
                        type: "POST",
                        url: "/Organization/UpdateModel",
                        data: JSON.stringify(cloneObj),
                        success: function (data) {
                            app.treeSelectNode.data.label = value;
                            if (data.Success) {
                                app.$message({
                                    type: 'success',
                                    message: '重命名完成'
                                });
                            }
                        }, error() {
                            app.$message.error("重命名失败!");
                        }
                    });
                }).catch(() => {
                    return false;
                })
            },
            addTab(data, node, self) {
                require(['LinqJS', 'OrganizationUserComponent'], function () {
                    app.treeSelectNode = node;
                    let newTabName = app.treeSelectNode.data.label;
                    if (app.editableTabs.length > 0) {
                        var isExsit = Enumerable.From(app.editableTabs).Any(p => p.name == app.treeSelectNode.data.label);
                        if (isExsit) {
                            app.editableTabsValue = newTabName;
                            return;
                        }
                    }
                    app.editableTabs.push({
                        id: node.data.id,
                        title: newTabName,
                        name: newTabName,
                        content: 'organization-user'
                    });
                    app.editableTabsValue = newTabName;
                });
            },
            removeTab(targetName) {
                let tabs = this.editableTabs;
                let activeName = this.editableTabsValue;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                            }
                        }
                    });
                }
                this.editableTabsValue = activeName;
                this.editableTabs = tabs.filter(tab => tab.name !== targetName);
            },
            //树导航折叠的时候触发resize修改tab页的宽度
            onResize(obj) {
                this.$nextTick(() => {
                    if (app.$refs.tabsRef) {
                        for (i = 0; i < app.$refs.tabsRef.length; i++) {
                            if (obj.scrollWidth > obj.clientWidth || obj.scrollHeight > obj.clientHeight) {
                                var scrollWidth = obj.scrollWidth - obj.clientWidth;
                                app.$refs.tabsRef[i].$el.style.width = obj.scrollWidth - scrollWidth - 30 + "px";
                            }
                            else {
                                if (minWidth > obj.scrollWidth && minWidth == 0) {
                                    minWidth = obj.scrollWidth
                                    app.$refs.tabsRef[i].$el.style.width = obj.scrollWidth - 10 + "px";
                                }
                                else {
                                    app.$refs.tabsRef[i].$el.style.width = obj.scrollWidth - 50 + "px";
                                }
                            }
                        }
                    }
                });
            }
        }
    })
})

上面就是左边的导航树及主要界面,下面给出Tab页里的组件,这个实例就比较完整了

Vue.component('organization-user', {
    template: `
`, props: { organizationId: { type: String }, }, data() { return { radio: '', userSelectShow: false, //表头 headerGroup: [ { label: 'id', prop: 'id', show: false, width: "160px" }, { label: '组织机构', prop: 'organization_name', show: true, width: "160px" }, { label: '用户账号', prop: 'user_name', show: true, width: "160px" }, { label: '用户名称', prop: 'full_name', show: true, width: "auto" } ], //搜索 search: { field_name: null, field_value: null }, //表格 table: { height: "300px", data: [], count: 0 }, //分页 GridPageRequest: { PageSize: 20, PageIndex: 0, PageTotal: 0, Filter: [] }, selectedRows: [], BusinessModel: { width: "100px", show: false, title: "新增", model: { id: "", user_name: "", password: "", full_name: "", validate_status: "", createby: "", create_time: "", updateby: "", update_time: "", remarks: "", Items: [] //明细 }, tag: { //公共资源 validate_status: { 1001: "启用", 1002: "禁用" } } } } }, mounted() { var that = this; this.$nextTick(() => { that.getTableData(); let resize = window.onresize = function () { that.table.height = $(window).height() - 150 + "px"; }; resize(); }); }, methods: { //选择行 handleSelectedRow(selection, row) { if (selection && selection.length > 0) { this.selectedRows = selection; } else { this.selectedRows = []; } }, //全选 handleSelectedAllRow(selection) { this.selectedRows = selection; }, //选择用户的事件 onDelete() { var that = this; var ids = this.selectedRows.map((o) => o.id); if (ids.length == 0) { this.$message.error("请选择用户!"); return; } var ids = this.selectedRows.map((o) => o.id); this.$confirm('是否确认操作所选择的行?', "删除", { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { $.ajax({ type: "POST", url: "/OrganizationUser/DeleteModel", data: JSON.stringify({ "ids": ids }), datatype: "json", success: function (data) { //绑定数据 if (data.Success) { that.$message({ message: '操作成功!', type: 'success' }); that.onSearch(); } }, error() { that.$message.error("操作失败!"); } }); }).catch(() => { this.$message({ type: 'info', message: '已取消' }); }); }, //搜索 onSearch() { this.search = this.search; this.GridPageRequest.Filter = []; if (this.search.field_name && this.search.field_name.length > 0 && this.search.field_value && this.search.field_value.length > 0) { this.GridPageRequest.Filter.push({ "Operator": "and", "Where": this.search.field_name + " like " + "'%" + this.search.field_value + "%'" }); } this.getTableData(); }, //请求表格数据 getTableData() { this.GridPageRequest.Filter.push({ "Operator": "and", "Where": "b.id =" + "'" + this.organizationId + "'" }); let loading = this.$loading(); var that = this; $.ajax({ type: "POST", url: "/OrganizationUser/LoadPageData", data: JSON.stringify(Object.assign(that.GridPageRequest)), success: function (data) { if (data.Success) { that.table.data = data.Data; that.table.count = data.TotalRows; } loading.close(); }, error() { that.$message.error("请求失败!"); loading.close(); } }); }, //修改分页大小 onPageSizeChange(now) { this.GridPageRequest.PageSize = now; this.getTableData(); }, //修改分页页数 onPageCurrentChange(now) { this.GridPageRequest.PageIndex = now; this.getTableData(); }, clearSearchText() { this.search.field_name = ""; this.GridPageRequest.Filter = []; }, clearSearchValue() { this.search.field_value = ""; this.GridPageRequest.Filter = []; }, onSelectUser() { var that = this; require(['UserSelectComponent'], function () { that.userSelectShow = true; }); }, CloseUserSelect() { this.userSelectShow = false; }, afterUserSelect(ids) { var that = this; $.ajax({ type: "POST", url: "/OrganizationUser/NewModels", data: JSON.stringify({ organizationId: that.organizationId, userIds: ids }), success: function (data) { if (data.Success) { that.getTableData(); that.$message({ type: 'success', message: '操作完成!' }); } }, error() { that.$message.error("操作完成!"); } }); } } });

 

你可能感兴趣的:(Vue.js)