GitBucket
4.6.0
Toggle navigation
Sign in
Files
Branches
1
Tags
Issues
Pull Requests
Labels
Milestones
Wiki
08335
/
hivui-platform-template
hivui平台项目模板
Browse code
下推标签页
master
1 parent
50acc16
commit
cb9af1ae5dd4bb5520f096432518fc09b9a706d1
20278
authored
on 30 Sep 2021
Showing
3 changed files
project/hivuiMain/store/modules/user.js
project/hivuiMain/utils/index.js
project/hivuiMain/views/layout/components/Main.vue
Ignore Space
Show notes
View
project/hivuiMain/store/modules/user.js
import {baseLogin, logout} from '@main/api/login' import { getToken, setToken, removeToken } from '@main/utils/auth' import md5 from 'md5' if(window.Scp==null){ window.Scp = {} } if(window.Scp.User==null){ window.Scp.User={} } const user = { namespaced: true, state: { token: getToken(), avatar: '', introduction: '', roles: [], //后面加的 userInfo: {}, id:Scp.User.id, name:Scp.User.name, deptId:Scp.User.deptId, deptName:Scp.User.deptName, positionId:Scp.User.positionId, postionName:Scp.User.postionName, bzId:Scp.User.bzId, bzName:Scp.User.bzName, bzDeptId:Scp.User.bzDeptId, bzDeptName:Scp.User.bzDeptName, bzPositionId:Scp.User.bzPositionId, bzPositionName:Scp.User.bzPositionName, orgId:Scp.User.orgId , defOrgId:Scp.User.defOrgId }, mutations: { SET_CODE: (state, code) => { state.code = code }, SET_TOKEN: (state, token) => { state.token = token }, SET_INTRODUCTION: (state, introduction) => { state.introduction = introduction }, SET_NAME: (state, name) => { state.name = name }, SET_AVATAR: (state, avatar) => { state.avatar = avatar }, SET_ROLES: (state, roles) => { state.roles = roles }, SET_USERINFO: (state, userInfo) => { state.userInfo = userInfo } }, actions: { load({ commit, state }) { }, // user login login({ commit }, userInfo) { const { username, password } = userInfo return new Promise((resolve, reject) => { baseLogin({ username: username.trim(), password: md5(password) }).then(response => { const data = response commit('SET_TOKEN', data.token) setToken(data.token) resolve() }).catch(error => { reject(error) }) }) }, // get user info getInfo({ commit, state }) { return new Promise((resolve, reject) => { debugger;getInfo(state.token).then(response => { if (!response.dataPack) { reject('Verification failed, please Login again.') } //const { info ,org} = response.data; const info = response.dataPack // if (!info) { // reject('Verification failed, please Login again.') // } //const { roles, name, avatar, introduction } = data let roles = ['admim'], avatar = "", introduction = "", name = info.fuserid, userInfo = { bzid: info.fbzid, id: info.fuserid, name: info.fusername, weixin: info.fweixin, qq: info.fqq, mbPhone: info.fmbphone, email: info.femail, roleid: info.froleid, rolename: info.frolename, enterpriseid: info.fenterpriseid, enterprisename: info.fenterprisename, shopid: info.fshopid, shopname: info.fshopname, //org } // roles must be a non-empty array if (!roles || roles.length <= 0) { reject('getInfo: roles must be a non-null array!') } commit('SET_USERINFO', userInfo) commit('SET_ROLES', roles) commit('SET_NAME', name) commit('SET_AVATAR', avatar) commit('SET_INTRODUCTION', introduction) resolve(info) }).catch(error => { reject(error) }) }) }, // user logout logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { commit('SET_TOKEN', '') commit('SET_ROLES', []) removeToken() resolve() }).catch(error => { reject(error) }) }) }, // remove token resetToken({ commit }) { return new Promise(resolve => { commit('SET_TOKEN', '') commit('SET_ROLES', []) removeToken() resolve() }) }, // dynamically modify permissions changeRoles({ commit, dispatch }, role) { return new Promise(async resolve => { const token = role + '-token' commit('SET_TOKEN', token) setToken(token) const { roles } = await dispatch('getInfo') //resetRouter() // generate accessible routes map based on roles const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true }) // dynamically add accessible routes router.addRoutes(accessRoutes) // reset visited views and cached views dispatch('tagsView/delAllViews', null, { root: true }) resolve() }) } } } export default user
import {baseLogin, logout} from '@main/api/login' import { getToken, setToken, removeToken } from '@main/utils/auth' import md5 from 'md5' if(window.Scp==null){ window.Scp = {} } if(window.Scp.User==null){ window.Scp.User={} } const user = { namespaced: true, state: { token: getToken(), avatar: '', introduction: '', roles: [], //后面加的 userInfo: {}, id:Scp.User.id, name:Scp.User.name, deptId:Scp.User.deptId, deptName:Scp.User.deptName, positionId:Scp.User.positionId, postionName:Scp.User.postionName, bzId:Scp.User.bzId, bzName:Scp.User.bzName, bzDeptId:Scp.User.bzDeptId, bzDeptName:Scp.User.bzDeptName, bzPositionId:Scp.User.bzPositionId, bzPositionName:Scp.User.bzPositionName, orgId:Scp.User.orgId , defOrgId:Scp.User.defOrgId }, mutations: { SET_CODE: (state, code) => { state.code = code }, SET_TOKEN: (state, token) => { state.token = token }, SET_INTRODUCTION: (state, introduction) => { state.introduction = introduction }, SET_NAME: (state, name) => { state.name = name }, SET_AVATAR: (state, avatar) => { state.avatar = avatar }, SET_ROLES: (state, roles) => { state.roles = roles }, SET_USERINFO: (state, userInfo) => { state.userInfo = userInfo } }, actions: { load({ commit, state }) { }, // user login login({ commit }, userInfo) { const { username, password } = userInfo return new Promise((resolve, reject) => { baseLogin({ username: username.trim(), password: md5(password) }).then(response => { const data = response commit('SET_TOKEN', data.token) setToken(data.token) resolve() }).catch(error => { reject(error) }) }) }, // get user info getInfo({ commit, state }) { /*return new Promise((resolve, reject) => { getInfo(state.token).then(response => { if (!response.dataPack) { reject('Verification failed, please Login again.') } //const { info ,org} = response.data; const info = response.dataPack // if (!info) { // reject('Verification failed, please Login again.') // } //const { roles, name, avatar, introduction } = data let roles = ['admim'], avatar = "", introduction = "", name = info.fuserid, userInfo = { bzid: info.fbzid, id: info.fuserid, name: info.fusername, weixin: info.fweixin, qq: info.fqq, mbPhone: info.fmbphone, email: info.femail, roleid: info.froleid, rolename: info.frolename, enterpriseid: info.fenterpriseid, enterprisename: info.fenterprisename, shopid: info.fshopid, shopname: info.fshopname, //org } // roles must be a non-empty array if (!roles || roles.length <= 0) { reject('getInfo: roles must be a non-null array!') } commit('SET_USERINFO', userInfo) commit('SET_ROLES', roles) commit('SET_NAME', name) commit('SET_AVATAR', avatar) commit('SET_INTRODUCTION', introduction) resolve(info) }).catch(error => { reject(error) }) })*/ }, // user logout logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { commit('SET_TOKEN', '') commit('SET_ROLES', []) removeToken() resetRouter() resolve() }).catch(error => { reject(error) }) }) }, // remove token resetToken({ commit }) { return new Promise(resolve => { commit('SET_TOKEN', '') commit('SET_ROLES', []) removeToken() resolve() }) }, // dynamically modify permissions changeRoles({ commit, dispatch }, role) { return new Promise(async resolve => { const token = role + '-token' commit('SET_TOKEN', token) setToken(token) const { roles } = await dispatch('getInfo') //resetRouter() // generate accessible routes map based on roles const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true }) // dynamically add accessible routes router.addRoutes(accessRoutes) // reset visited views and cached views dispatch('tagsView/delAllViews', null, { root: true }) resolve() }) } } } export default user
Ignore Space
Show notes
View
project/hivuiMain/utils/index.js
import getScroll from './getScroll' export function getTargetRect(target) { return target !== window ? target.getBoundingClientRect() : { top: 0, left: 0, bottom: 0 }; } export function getOffset(element, target) { const elemRect = element.getBoundingClientRect(); const targetRect = getTargetRect(target); const scrollTop = getScroll(target, true); const scrollLeft = getScroll(target, false); const docElem = window.document.body; const clientTop = docElem.clientTop || 0; const clientLeft = docElem.clientLeft || 0; return { top: elemRect.top - targetRect.top + scrollTop - clientTop, left: elemRect.left - targetRect.left + scrollLeft - clientLeft, width: elemRect.width, height: elemRect.height, }; } export function getDefaultTarget() { return typeof window !== 'undefined' ? window : null; } /** * @method setUrlValue * @description 设置地址栏参数值 * @param url * @param pName * @param pValue * * @example: urlAppend("http://www.fdauto.com","userid=03870");�����http://www.fdauto.com?userid=03870;1` * urlAppend("http://www.fdauto.com?userid=03870","bumen=aj")�����http://www.fdauto.com?userid=03870&bumen=aj; */ export function setUrlValue(url, key, value) { var returnUrl = '' if (url.indexOf('?') == -1) { returnUrl += url + '?' + key + '=' + value } else { if (url.indexOf('?' + key + '=') == -1 && url.indexOf('&' + key + '=') == -1) { returnUrl += url + '&' + key + '=' + value } else { var isDone = false var startIndex = 0 var endIndex = url.length - 1 var parm = '?' + key + '=' for (var i = 0; i < url.length; i++) { if (url.substr(i, parm.length) == parm) { startIndex = i + parm.length for (var j = startIndex; j < url.length; j++) { if (url[j] == '&') { endIndex = j break } else if (j == url.length - 1) { endIndex = url.length } } isDone = true break } } if (!isDone) { parm = '&' + key + '=' for (var i = 0; i < url.length; i++) { if (url.substr(i, parm.length) == parm) { startIndex = i + parm.length for (var j = startIndex; j < url.length; j++) { if (url[j] == '&') { endIndex = j break } else if (j == url.length - 1) { endIndex = url.length } } break } } } var parmKeyValue = parm + url.substring(startIndex, endIndex) returnUrl = url.replace(parmKeyValue, parm + value) } } return returnUrl } /** * @method getUrlValue * @description 获取地址栏参数值 * @param name * string * @param url * string * @example: getUrlValue("p","http://www.baidu.com?p=5"); */ export function getUrlValue(url, name) { var str = url || window.location.search; if (str.indexOf("&" + name) != -1 || str.indexOf("?" + name) != -1) { var pos_start = "" if (str.indexOf("?" + name) > -1) pos_start = str.indexOf("?" + name) + name.length + 2; else pos_start = str.indexOf("&" + name) + name.length + 2; var pos_end = str.indexOf("&", pos_start); if (pos_end == -1) { return str.substring(pos_start); } else { return str.substring(pos_start, pos_end) } } else { return ""; } } export function getUrlSearch(url) { var name, value; var str = url; //取得整个地址栏 var num = str.indexOf("?") str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ] var arr = str.split("&"); //各个参数放到数组里 var search ={}; for (var i = 0; i < arr.length; i++) { num = arr[i].indexOf("="); if (num > 0) { name = arr[i].substring(0, num); value = arr[i].substr(num + 1); search[name] = value; } } return search; } /** * var str='这是一个测试的字符串:{0} {1}'.format('Hello','world'); * var str='这是一个测试的字符串:{str0} {str1}'.format({str0:'Hello',str1:'world'}); */ export function strFormat(str, args) { var result = str; if (arguments.length > 0) { if (arguments.length == 2 && typeof (args) == "object") { for (var key in args) { if (args[key] != undefined) { var reg = new RegExp("({" + key + "})", "g"); result = result.replace(reg, args[key]); } } } else { for (var i = 1; i < arguments.length; i++) { if (arguments[i] != undefined) { var reg = new RegExp("({)" + (i - 1) + "(})", "g"); result = result.replace(reg, arguments[i]); } } } } return result; } export function closeWindow(errorUrl){ if (document.all) { if (window.location.pathname == window.parent.location.pathname) { window.opener = null; window.open('', '_top'); window.top.close(); } } else { window.close(); } window.location.href = errorUrl || "about:blank"; }
import getScroll from './getScroll' export function getTargetRect(target) { return target !== window ? target.getBoundingClientRect() : { top: 0, left: 0, bottom: 0 }; } export function getOffset(element, target) { const elemRect = element.getBoundingClientRect(); const targetRect = getTargetRect(target); const scrollTop = getScroll(target, true); const scrollLeft = getScroll(target, false); const docElem = window.document.body; const clientTop = docElem.clientTop || 0; const clientLeft = docElem.clientLeft || 0; return { top: elemRect.top - targetRect.top + scrollTop - clientTop, left: elemRect.left - targetRect.left + scrollLeft - clientLeft, width: elemRect.width, height: elemRect.height, }; } export function getDefaultTarget() { return typeof window !== 'undefined' ? window : null; } /** * @method setUrlValue * @description 设置地址栏参数值 * @param url * @param pName * @param pValue * * @example: urlAppend("http://www.fdauto.com","userid=03870");�����http://www.fdauto.com?userid=03870;1` * urlAppend("http://www.fdauto.com?userid=03870","bumen=aj")�����http://www.fdauto.com?userid=03870&bumen=aj; */ export function setUrlValue(url, key, value) { var returnUrl = '' if (url.indexOf('?') == -1) { returnUrl += url + '?' + key + '=' + value } else { if (url.indexOf('?' + key + '=') == -1 && url.indexOf('&' + key + '=') == -1) { returnUrl += url + '&' + key + '=' + value } else { var isDone = false var startIndex = 0 var endIndex = url.length - 1 var parm = '?' + key + '=' for (var i = 0; i < url.length; i++) { if (url.substr(i, parm.length) == parm) { startIndex = i + parm.length for (var j = startIndex; j < url.length; j++) { if (url[j] == '&') { endIndex = j break } else if (j == url.length - 1) { endIndex = url.length } } isDone = true break } } if (!isDone) { parm = '&' + key + '=' for (var i = 0; i < url.length; i++) { if (url.substr(i, parm.length) == parm) { startIndex = i + parm.length for (var j = startIndex; j < url.length; j++) { if (url[j] == '&') { endIndex = j break } else if (j == url.length - 1) { endIndex = url.length } } break } } } var parmKeyValue = parm + url.substring(startIndex, endIndex) returnUrl = url.replace(parmKeyValue, parm + value) } } return returnUrl } /** * @method getUrlValue * @description 获取地址栏参数值 * @param name * string * @param url * string * @example: getUrlValue("p","http://www.baidu.com?p=5"); */ export function getUrlValue(url, name) { var str = url || window.location.search; if (str.indexOf("&" + name) != -1 || str.indexOf("?" + name) != -1) { var pos_start = "" if (str.indexOf("?" + name) > -1) pos_start = str.indexOf("?" + name) + name.length + 2; else pos_start = str.indexOf("&" + name) + name.length + 2; var pos_end = str.indexOf("&", pos_start); if (pos_end == -1) { return str.substring(pos_start); } else { return str.substring(pos_start, pos_end) } } else { return ""; } } export function getUrlSearch(url) { var name, value; var str = url; //取得整个地址栏 var num = str.indexOf("?") str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ] var arr = str.split("&"); //各个参数放到数组里 var search ={}; for (var i = 0; i < arr.length; i++) { num = arr[i].indexOf("="); if (num > 0) { name = arr[i].substring(0, num); value = arr[i].substr(num + 1); search[name] = value; } } return search; } /** * var str='这是一个测试的字符串:{0} {1}'.format('Hello','world'); * var str='这是一个测试的字符串:{str0} {str1}'.format({str0:'Hello',str1:'world'}); */ export function strFormat(str, args) { var result = str; if (arguments.length > 0) { if (arguments.length == 2 && typeof (args) == "object") { for (var key in args) { if (args[key] != undefined) { var reg = new RegExp("({" + key + "})", "g"); result = result.replace(reg, args[key]); } } } else { for (var i = 1; i < arguments.length; i++) { if (arguments[i] != undefined) { var reg = new RegExp("({)" + (i - 1) + "(})", "g"); result = result.replace(reg, arguments[i]); } } } } return result; }
Ignore Space
Show notes
View
project/hivuiMain/views/layout/components/Main.vue
<template> <div class="pl-main"> <p-tabs ref="cmp-tabs" v-model="defTabKey" @onActiveTab="handleActiveTab" @onRemoveTab="handleRemoveTab" @onRemoveAllTab="handleRemoveAllTab" @onRemoveLeft="handleRemoveLeftTab" @onRemoveRight="handleRemoveRightTab" @onRemoveOther="handleRemoveOtherTab" @onFullScreen="handleFullScreen" > <p-tabpanel v-for="(item,index) in tabList" :key="item.id" :close="item.close" :title.sync="item.title" :name="item.id" :url="item.url" :itemData="item" @onIframeLoad="handleIframeLoad" @onBeforeClose="handleBeforeClose" @onSelected="handleSelected" @onBeforeRefresh="handleBeforeRefresh" > <template v-if="item.type&&item.type=='home'"> <PortalSys :itemData="item" ref="protalSysHome" ></PortalSys> </template> <template v-if="item.type&&item.type=='work'"> <PortalUser :itemData="item" ref="portalUserWork" ></PortalUser> </template> </p-tabpanel> </p-tabs> </div> </template> <script> import { baseURL, codeProjectName,requestUrl } from "@main/config"; import { PTabs, PTabpanel } from "@main/components/tabpanel"; import PortalUser from "@main/views/Portal/user"; import PortalSys from "@main/views/Portal/sys"; import { getUrlValue, setUrlValue,getUrlSearch,closeWindow } from "@main/utils"; // import { type } from "os"; import md5 from "md5"; import { utils } from "hi-ui"; export default { inject: ["addTab", "showTab", "hideTab"], components: { PTabs, PTabpanel, PortalUser, PortalSys, }, data() { debugger let cfg = this.$store.state.app.config || {}; let defTabs = cfg.sysDefTabs || []; let setTabs = cfg.sysSetTabs || []; let list = [], defTabKey = ""; defTabs = setTabs.concat(defTabs); defTabs.map((item, i) => { let id = item.url ? md5(item.url) : item.id; //强转成 url md5 id item.actived && (defTabKey = id); if (item.url && getUrlValue(item.url, "__tabId") == "") { //关系到用户调用,防止Scp.context.closeCurPage取不到__tabId出错 item.url = utils.string.setUrlValue(item.url, "__tabId", id); } list.push({ title: item.title, url: item.url, close: item.close, id: id, type: item.type, }); }); console.log('page default open tabs :',defTabs); //系统菜单 后台默认配激活 let menusDef2Tabs = this.$store.getters.defTabs, uriStr = ""; console.log('menus default open tabs :',defTabs); menusDef2Tabs.map((item, i) => { uriStr = baseURL + codeProjectName + item.resUrl; let id = md5(uriStr); uriStr = utils.string.setUrlValue(uriStr, "__tabId", id); list.push({ title: item.name, url: uriStr, close: true, id: id, type: item.type, }); }); // console.log('系统菜单',list); //第三方跳转过来地址自动打开功能tab let menusList = this.$store.getters.menusList; let searchObj = getUrlSearch(decodeURIComponent(this.$router.currentRoute.fullPath)); for (let i = menusList.length - 1; i >= 0; i--) { if ((menusList[i].type=="func"||menusList[i].type=="flow" )&& searchObj.portal_func == menusList[i].resUrl) { console.log('跳转进来的功能:',searchObj.portal_func); //?portal_func=/project/rjwhzx/rjzcgl/funcdir/zcmcx.func&id=11111 delete searchObj.portal_func; let uriStr = baseURL + codeProjectName + menusList[i].resUrl; let id = md5(uriStr); uriStr = utils.string.setUrlValue(uriStr, "__tabId", md5(uriStr)); for(let key in searchObj){ uriStr = utils.string.setUrlValue(uriStr,key,searchObj[key]); } let inMenu = false; for (let j = list.length - 1; j >= 0; j--) { if (list[j].id == id) { inMenu = true; break; } } if (inMenu) break; defTabKey = id; list.push({ id: id, title: menusList[i].name, url: uriStr, close: true, actived:true //默认选中 }); break; } } debugger console.log('sys default tabs :', list); return { defTabKey: defTabKey || "", tabList: list, sysConfig: this.$store.state.app.config, isFullScreen: false, }; }, mounted() { // console.log('主界面初始化~!'); let me = this, cTabs = this.$refs["cmp-tabs"]; window.Sys = { isVue: true, addEvent(evtName, fn) { //onLoad Bus.$on(evtName, fn); }, tabPanel: { autoResize() { cTabs.resize(); }, }, getSideNavs() { return [...me.$store.getters.navs]; }, setSideNavs(data) { if (data == null && !(data instanceof Array)) return; //me.$store.dispatch("app/setQuickNav", data); }, /** * @param {} url * @param {} title * @param {} uid * @param {} onLoad //iframe 加载后 * @param {} nearest //标签页是否紧接在其右侧打开 * @param {} renderedFn //渲染回调 */ addTab(url, title, uid, onLoad, nearest, renderedFn) { if (!(url == "" || url == "about:blank")) { uid = md5(url); } let tabs = me.tabList.filter((item, index) => { return item.id == uid; }); if (tabs.length) { me.defTabKey = uid; me.$nextTick( (function (fn) { return function () { let tab = cTabs.getItemObj(uid); fn && fn(tab); }; })(renderedFn) ); return; } if (getUrlValue(url, "__tabId") == "") { //关系到用户调用,防止Scp.context.closeCurPage取不到__tabId出错 url = utils.string.setUrlValue(url, "__tabId", uid); } me.tabList.push({ title: title, url: url, close: true, id: uid, listeners: { load: onLoad, }, }); me.defTabKey = uid; // window.____renderFunc = renderedFn; me.$nextTick( (function (fn, _uid) { return function () { let tab = cTabs.getItemObj(_uid); fn && fn(tab); }; })(renderedFn, uid) ); console.log(' addTab ',me.tabList); }, getTab(uid) { return cTabs.getItemObj(uid); }, seldTab(uid) { cTabs.defTabKey = uid; }, getSeldTab() { return cTabs.getSeldItemObj(); }, refreshTab(uid) { let tab = cTabs.getItemObj(uid); tab && tab.tabPanelIframeEl.contentWindow.window.location.reload(); }, //closeTab colseTab(uid) { cTabs.closeItem(uid); }, colseSeldTab() { cTabs.closeCurItem(); }, }; window.SysPage={ newPage : function(title, url, params, method, target) { var uid = md5(url), tab; debugger function formSubmit(cfg){ debugger cfg.autoDestroy = true; var form = me.creatForm(cfg); form.submit(); } if(method=="get"){ //get 不刷新 var tab = top.Sys.getTab(uid); if(tab){ top.Sys.seldTab(uid); return; } } if(target=="opening"){ var cfg = { url : utils.string.setUrlValue(url,"__tabId",uid), data : params, target : '_blank', method : method || "get" }; formSubmit(cfg); //打开新标签 return; }else if(target=="me"){ //本页:框架页的本页面 var cfg = { url : url, data : params, target : '_self', method : method || "get" }; formSubmit(cfg); }else{ if (target == "_self"){ tab = top.Sys.getSeldTab(); if(top.Sys.isVue){ var titleEl = tab.tabEl.querySelector('.pl-tabs-itemTxt'); titleEl.innerText = ""; }else{ tab.tabEl.find('.sys-tab-item-text').html(""); } }else{ /*** * uid 让框架页可以关闭自己 closeCurPage */ if(top.Sys.isVue){ //6个参数,第7个是vue渲染后回调 top.Sys.addTab("about:blank",title,uid,null,true,function(tab){ var cfg = { url : utils.string.setUrlValue(url,"__tabId",uid), data : params, target : null, method : method || "get" }; //var titleEl = tab.tabEl.querySelector('.pl-tabs-itemTxt'); //titleEl.innerText = ""; cfg.target = tab.tabPanelIframeEl.getAttribute('name'); formSubmit(cfg); }); }else{ var cfg = { url : utils.string.setUrlValue(url,"__tabId",uid), data : params, target : null, method : method || "get" }; //Sys.addTab(url, title, uid, callback) tab = top.Sys.addTab("about:blank",title,uid); tab.tabEl.find('.sys-tab-item-text').html(""); cfg.target = tab.tabPanelIframeEl.getAttribute('name'); formSubmit(cfg); } } } }, /** * 通过url 进行对应的目标功能 调用目标页的callback方法 * @param id * @param url */ closePage : function(id,url) { if (!top.Sys) { closeWindow() return; } var uid = md5(url||""), tab; if(!window.parent.Sys){ return; } var tab = window.parent.Sys.getTab(uid); if(tab){ window.parent.Sys.seldTab(uid); //var _scp = tab.tabPanelIframeEl.contentWindow.window.Scp; //if(_scp){ // _scp.context&&_scp.context.callback&&_scp.context.callback.call(_scp.context); //} }else{ if(url.trim()!=""){ var tab = window.parent.Sys.addTab(url,"",null,null,true); } } if (id) { window.parent.Sys.colseTab(id); }else{ window.parent.Sys.colseSeldTab(); } }, closeCurPage:function(){ if(!window.parent.Sys){ return; } var id = getUrlValue('__tabId',window.location.search); window.parent.Sys.colseTab(id); }, setPageTitle:function(title){ if(!window.parent.Sys){ return; } var openway = getUrlValue('openway'); if(openway=="openwin")return; var tab = window.parent.Sys.getSeldTab(); if(title!=""){ tab.tabEl.find('.sys-tab-item-text').html(title); window.parent.Sys.tabPanel.autoResize(); } } }; if (this.defTabKey == "" && this.tabList.length) this.defTabKey = this.tabList[0].id; //默认如果指向下面两个的话,标识一下已经加载过 if (this.$refs["protalSysHome"]) { //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表 // console.log('加载系统门户列表~!'); let itemData = this.$refs["protalSysHome"][0].itemData; if (itemData.id == this.defTabKey) { this.$refs["protalSysHome"][0].actived = true; } } if (this.$refs["portalUserWork"]) { //this.$store.dispatch("portal/loadList"); //重新加载工作台门户列表 // console.log('加载工作台门户列表~!'); let itemData = this.$refs["portalUserWork"][0].itemData; if (itemData.id == this.defTabKey) { this.$refs["portalUserWork"][0].actived = true; } } let events = this.sysConfig.events; if (events) { this.$nextTick((r) => { events.onLoad && events.onLoad(); }); } }, methods: { //将框架页里头的a 标签进行转换 initATagUrl(el) { let aList = el.querySelectorAll("a"); aList.forEach(function (aTag, i) { if (aTag.href) { var httpUrl = new RegExp( "^((https|http|ftp|rtsp|mms)?://)" ); if ( httpUrl.test( aTag.href.replace(window.location.origin, "") ) ) { return false; } if (!aTag.onclick) { if (aTag.target == "_blank") { aTag.addEventListener("click", function (evt) { evt.preventDefault(); evt.stopPropagation(); var tabTitle = ""; if (aTag.title) { tabTitle = aTag.title; } var url = this.getAttribute("href"); var reg = /^\//gi; Sys.addTab(url, tabTitle, "", "", true); return false; }); } } } }); window.Sys.tabPanel.autoResize(); }, handleBeforeRefresh(panel, evt) { if (panel.itemData.type == "home") { // this.$store.state.app.sysList=[]; //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表 return false; } if (panel.itemData.type == "work") { // this.$store.state.app.list=[]; //this.$store.dispatch("portal/loadList"); //重新加载工作台门户列表 return false; } }, handleIframeLoad(panelCmp, evt) { let me = this, key = panelCmp.name; let ifm = panelCmp.$refs["iframe"]; let tabData = panelCmp.itemData; if (tabData.listeners) { tabData.listeners.load && tabData.listeners.load(); } //转换A标签 me.initATagUrl(ifm.contentWindow.document.body); window.__UserInfo = { orgId: "", operator: "", }; if (panelCmp.title == null || panelCmp.title == "") { let cTabs = me.$refs["cmp-tabs"]; cTabs.resize(); } }, handleBeforeClose(panel, evt) { let ifm = panel.$refs["iframe"]; try { let flag = ifm.contentWindow.Scp.context.beforeunloadFn(evt, 1); return flag; } catch (e) { !document.all && window.console.log( "iframe : Scp.context.beforeunloadFn();" ); } }, handleActiveTab(panel) { if (!panel) return; if (panel.itemData.type == "home") { this.$refs["protalSysHome"][0].doRender(); } if (panel.itemData.type == "work") { this.$refs["portalUserWork"][0].doRender(); } try { let tab = this.$refs["cmp-tabs"].getItemObj(panel.name); tab && tab.tabPanelIframeEl.contentWindow .$(tab.tabPanelIframeEl.contentDocument) .trigger("iframeActiving", [panel.name]); } catch (e) { console.log("iframeActiving error!"); } }, //面板上面的事件特别处理,现在暂时没用 handleSelected(item) { return; let key = item.id; let ifm = this.$refs["dom-iframe" + key][0]; try { let __orgId = ifm.contentWindow.Scp.User.getId(); let __operator = ifm.contentWindow.Scp.User.getOperator(); window.__UserInfo = { orgId: __orgId, operator: __operator, }; } catch (e) {} }, handleRemoveTab(targetName) { let tabs = this.tabList; let activeName = this.defTabKey; if (activeName === targetName) { tabs.forEach((tab, index) => { if (tab.close && tab.id === targetName) { let nextTab = tabs[index + 1] || tabs[index - 1]; if (nextTab) { activeName = nextTab.id; } } }); } this.defTabKey = activeName; tabs = tabs.filter((tab) => { return tab.close == false || tab.id !== targetName; }); console.log('handleRemoveTab') this.$set(this, "tabList", tabs); if (this.tabList.length == 0) { this.defTabKey = "tabPanel_home"; } }, handleRemoveAllTab() { let tabs = this.tabList; this.tabList = tabs.filter((tab) => { return !tab.close; }); let l = this.tabList.length; this.defTabKey = l ? this.tabList[l - 1].id : ""; }, handleRemoveLeftTab(name, index) { let tabs = this.tabList; let defTabKey = this.defTabKey; this.tabList = tabs.filter((tab, i) => { if (tab.id == defTabKey && i < index) { //当前的选中,是在关闭区内 defTabKey = name; } return tab.close == false || i >= index; }); this.defTabKey = defTabKey; }, handleRemoveRightTab(name, index) { let tabs = this.tabList; let defTabKey = this.defTabKey; this.tabList = tabs.filter((tab, i) => { if (tab.id == defTabKey && i > index) { //当前的选中,是在关闭区内 defTabKey = name; } return tab.close == false || i <= index; }); this.defTabKey = defTabKey; }, handleRemoveOtherTab(name, index) { let tabs = this.tabList; tabs = tabs.filter((tab, i) => { return tab.close == false || i == index; }); this.$set(this, "tabList", tabs); this.defTabKey = name; }, handleFullScreen() { this.$emit("onFullScreen"); // screenfull.toggle() }, creatForm(opt){ debugger;let that=this; var _opt={ autoShow:false, cancelAction:false, url:null, target:null, action:null, method:null, params:null, data:null, autoDestroy:false, _id:utils.string.id(8), }; Object.assign(_opt,opt); var _formTpl=`<form id="${_opt._id}"><input type="submit" value="submit" id="submit_${_opt._id}"/></form>`; var _el=document.createElement("div"); _el.innerHTML=_formTpl; document.getElementsByTagName("body")[0].appendChild(_el); var _form=_el.getElementsByTagName("form")[0]; this.setTarget=(str)=>{ _opt.target = str; _form.setAttribute('target',str); } this.setUrl=(str)=>{ this.formateUrl(str); var url = utils.string.setUrlValue(_opt.url,"_____r",new Date().getTime()); _form.setAttribute('action',url); } this.setMethod=(str)=>{ _opt.method = str||'get'; _form.setAttribute('method',str); } this.setParams=(params)=>{ _opt.params = params; } this.setData=(obj)=>{ _opt.data = obj||{}; if(_opt.method=="get"&&_opt.url!=null){ var parms =_opt.url.split("?")[1], item,i=0,len; if(parms!=null){ parms = parms.split("&"); for(i=0,len=parms.length;i<len;i++){ item = parms[i].split("="); _opt.data[item[0]]=item[1]; } } } _.each(_opt.data,function(value,key){ if(_.isObject(value)){ value = JSON.stringify(value); } var _hiddenInput=document.createElement("input"); _hiddenInput.setAttribute("type","hidden"); _form.appendChild(_hiddenInput); _form.setAttribute('name',key); _form.setAttribute('value',value); }); } this.removeData=()=>{ _opt.data = null; _form.children().remove(); } this.addData=(data)=>{ _opt.data = _.extend({},_opt.data||{},data||{}); _form.children().remove(); this.setData(_opt.data); } this.delData=(keys)=>{ _.each(keys||[],function(val,i){ if((val in _opt.data)){ delete _opt.data[val]; } }); _form.children().remove(); this.setData(_opt.data); } this.formateUrl=(url)=>{ var params= this.formateParams(_opt.params); if(!url)return; _opt.url = url; if(params){ if(_opt.url.indexOf('?')>0){ _opt.url+='&'+params; }else{ _opt.url+='?'+params; } } } this.formateParams=(obj)=>{ if(obj==null) return null; return $.param(obj||{}); } this.submit=()=>{ if(_opt.cancelAction) return; _opt.cancelAction = false; if(_opt.autoDestroy){ setTimeout(function(){ _form.submit() //_form.find('#submit'+me.id).click();//谷歌下面要用 按钮才有效果 },0); setTimeout(function(){that.destroy();},1000); }else{ _form.submit(); } } this.destroy=()=>{ _el.remove(); } this.setTarget(_opt.target); this.setMethod(_opt.method); this.setUrl(_opt.url); this.setData(_opt.data); return that; }, }, }; </script> <style scoped> </style>
<template> <div class="pl-main"> <p-tabs ref="cmp-tabs" v-model="defTabKey" @onActiveTab="handleActiveTab" @onRemoveTab="handleRemoveTab" @onRemoveAllTab="handleRemoveAllTab" @onRemoveLeft="handleRemoveLeftTab" @onRemoveRight="handleRemoveRightTab" @onRemoveOther="handleRemoveOtherTab" @onFullScreen="handleFullScreen" > <p-tabpanel v-for="(item,index) in tabList" :key="item.id" :close="item.close" :title.sync="item.title" :name="item.id" :url="item.url" :itemData="item" @onIframeLoad="handleIframeLoad" @onBeforeClose="handleBeforeClose" @onSelected="handleSelected" @onBeforeRefresh="handleBeforeRefresh" > <template v-if="item.type&&item.type=='home'"> <PortalSys :itemData="item" ref="protalSysHome" ></PortalSys> </template> <template v-if="item.type&&item.type=='work'"> <PortalUser :itemData="item" ref="portalUserWork" ></PortalUser> </template> </p-tabpanel> </p-tabs> </div> </template> <script> import { baseURL, codeProjectName,requestUrl } from "@main/config"; import { PTabs, PTabpanel } from "@main/components/tabpanel"; import PortalUser from "@main/views/Portal/user"; import PortalSys from "@main/views/Portal/sys"; import { getUrlValue, setUrlValue,getUrlSearch } from "@main/utils"; // import { type } from "os"; import md5 from "md5"; export default { inject: ["addTab", "showTab", "hideTab"], components: { PTabs, PTabpanel, PortalUser, PortalSys, }, data() { debugger let cfg = this.$store.state.app.config || {}; let defTabs = cfg.sysDefTabs || []; let setTabs = cfg.sysSetTabs || []; let list = [], defTabKey = ""; defTabs = setTabs.concat(defTabs); defTabs.map((item, i) => { let id = item.url ? md5(item.url) : item.id; //强转成 url md5 id item.actived && (defTabKey = id); if (item.url && getUrlValue(item.url, "__tabId") == "") { //关系到用户调用,防止Scp.context.closeCurPage取不到__tabId出错 item.url = setUrlValue(item.url, "__tabId", id); } list.push({ title: item.title, url: item.url, close: item.close, id: id, type: item.type, }); }); console.log('page default open tabs :',defTabs); //系统菜单 后台默认配激活 let menusDef2Tabs = this.$store.getters.defTabs, uriStr = ""; console.log('menus default open tabs :',defTabs); menusDef2Tabs.map((item, i) => { uriStr = baseURL + codeProjectName + item.resUrl; let id = md5(uriStr); uriStr = setUrlValue(uriStr, "__tabId", id); list.push({ title: item.name, url: uriStr, close: true, id: id, type: item.type, }); }); // console.log('系统菜单',list); //第三方跳转过来地址自动打开功能tab let menusList = this.$store.getters.menusList; let searchObj = getUrlSearch(decodeURIComponent(this.$router.currentRoute.fullPath)); for (let i = menusList.length - 1; i >= 0; i--) { if ((menusList[i].type=="func"||menusList[i].type=="flow" )&& searchObj.portal_func == menusList[i].resUrl) { console.log('跳转进来的功能:',searchObj.portal_func); //?portal_func=/project/rjwhzx/rjzcgl/funcdir/zcmcx.func&id=11111 delete searchObj.portal_func; let uriStr = baseURL + codeProjectName + menusList[i].resUrl; let id = md5(uriStr); uriStr = setUrlValue(uriStr, "__tabId", md5(uriStr)); for(let key in searchObj){ uriStr = setUrlValue(uriStr,key,searchObj[key]); } let inMenu = false; for (let j = list.length - 1; j >= 0; j--) { if (list[j].id == id) { inMenu = true; break; } } if (inMenu) break; defTabKey = id; list.push({ id: id, title: menusList[i].name, url: uriStr, close: true, actived:true //默认选中 }); break; } } debugger console.log('sys default tabs :', list); return { defTabKey: defTabKey || "", tabList: list, sysConfig: this.$store.state.app.config, isFullScreen: false, }; }, mounted() { // console.log('主界面初始化~!'); let me = this, cTabs = this.$refs["cmp-tabs"]; window.Sys = { isVue: true, addEvent(evtName, fn) { //onLoad Bus.$on(evtName, fn); }, tabPanel: { autoResize() { cTabs.resize(); }, }, getSideNavs() { return [...me.$store.getters.navs]; }, setSideNavs(data) { if (data == null && !(data instanceof Array)) return; //me.$store.dispatch("app/setQuickNav", data); }, /** * @param {} url * @param {} title * @param {} uid * @param {} onLoad //iframe 加载后 * @param {} nearest //标签页是否紧接在其右侧打开 * @param {} renderedFn //渲染回调 */ addTab(url, title, uid, onLoad, nearest, renderedFn) { if (!(url == "" || url == "about:blank")) { uid = md5(url); } let tabs = me.tabList.filter((item, index) => { return item.id == uid; }); if (tabs.length) { me.defTabKey = uid; me.$nextTick( (function (fn) { return function () { let tab = cTabs.getItemObj(uid); fn && fn(tab); }; })(renderedFn) ); return; } if (getUrlValue(url, "__tabId") == "") { //关系到用户调用,防止Scp.context.closeCurPage取不到__tabId出错 url = setUrlValue(url, "__tabId", uid); } me.tabList.push({ title: title, url: url, close: true, id: uid, listeners: { load: onLoad, }, }); me.defTabKey = uid; // window.____renderFunc = renderedFn; me.$nextTick( (function (fn, _uid) { return function () { let tab = cTabs.getItemObj(_uid); fn && fn(tab); }; })(renderedFn, uid) ); console.log(' addTab ',me.tabList); }, getTab(uid) { return cTabs.getItemObj(uid); }, seldTab(uid) { cTabs.defTabKey = uid; }, getSeldTab() { return cTabs.getSeldItemObj(); }, refreshTab(uid) { let tab = cTabs.getItemObj(uid); tab && tab.tabPanelIframeEl.contentWindow.window.location.reload(); }, //closeTab colseTab(uid) { cTabs.closeItem(uid); }, colseSeldTab() { cTabs.closeCurItem(); }, }; if (this.defTabKey == "" && this.tabList.length) this.defTabKey = this.tabList[0].id; //默认如果指向下面两个的话,标识一下已经加载过 if (this.$refs["protalSysHome"]) { //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表 // console.log('加载系统门户列表~!'); let itemData = this.$refs["protalSysHome"][0].itemData; if (itemData.id == this.defTabKey) { this.$refs["protalSysHome"][0].actived = true; } } if (this.$refs["portalUserWork"]) { //this.$store.dispatch("portal/loadList"); //重新加载工作台门户列表 // console.log('加载工作台门户列表~!'); let itemData = this.$refs["portalUserWork"][0].itemData; if (itemData.id == this.defTabKey) { this.$refs["portalUserWork"][0].actived = true; } } let events = this.sysConfig.events; if (events) { this.$nextTick((r) => { events.onLoad && events.onLoad(); }); } }, methods: { //将框架页里头的a 标签进行转换 initATagUrl(el) { let aList = el.querySelectorAll("a"); aList.forEach(function (aTag, i) { if (aTag.href) { var httpUrl = new RegExp( "^((https|http|ftp|rtsp|mms)?://)" ); if ( httpUrl.test( aTag.href.replace(window.location.origin, "") ) ) { return false; } if (!aTag.onclick) { if (aTag.target == "_blank") { aTag.addEventListener("click", function (evt) { evt.preventDefault(); evt.stopPropagation(); var tabTitle = ""; if (aTag.title) { tabTitle = aTag.title; } var url = this.getAttribute("href"); var reg = /^\//gi; console.log( "onload replace links href,on iframe ", Scp.Setting.appRoot, url ); if ( !reg.test(url) && url.indexOf(Scp.Setting.appRoot) < 0 ) { url = Scp.Setting.appRoot + url; } Sys.addTab(url, tabTitle, "", "", true); return false; }); } } } }); window.Sys.tabPanel.autoResize(); }, handleBeforeRefresh(panel, evt) { if (panel.itemData.type == "home") { // this.$store.state.app.sysList=[]; //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表 return false; } if (panel.itemData.type == "work") { // this.$store.state.app.list=[]; //this.$store.dispatch("portal/loadList"); //重新加载工作台门户列表 return false; } }, handleIframeLoad(panelCmp, evt) { let me = this, key = panelCmp.name; let ifm = panelCmp.$refs["iframe"]; let tabData = panelCmp.itemData; if (tabData.listeners) { tabData.listeners.load && tabData.listeners.load(); } //转换A标签 me.initATagUrl(ifm.contentWindow.document.body); window.__UserInfo = { orgId: "", operator: "", }; if (panelCmp.title == null || panelCmp.title == "") { let cTabs = me.$refs["cmp-tabs"]; cTabs.resize(); } }, handleBeforeClose(panel, evt) { let ifm = panel.$refs["iframe"]; try { let flag = ifm.contentWindow.Scp.context.beforeunloadFn(evt, 1); return flag; } catch (e) { !document.all && window.console.log( "iframe : Scp.context.beforeunloadFn();" ); } }, handleActiveTab(panel) { if (!panel) return; if (panel.itemData.type == "home") { this.$refs["protalSysHome"][0].doRender(); } if (panel.itemData.type == "work") { this.$refs["portalUserWork"][0].doRender(); } try { let tab = this.$refs["cmp-tabs"].getItemObj(panel.name); tab && tab.tabPanelIframeEl.contentWindow .$(tab.tabPanelIframeEl.contentDocument) .trigger("iframeActiving", [panel.name]); } catch (e) { console.log("iframeActiving error!"); } }, //面板上面的事件特别处理,现在暂时没用 handleSelected(item) { return; let key = item.id; let ifm = this.$refs["dom-iframe" + key][0]; try { let __orgId = ifm.contentWindow.Scp.User.getId(); let __operator = ifm.contentWindow.Scp.User.getOperator(); window.__UserInfo = { orgId: __orgId, operator: __operator, }; } catch (e) {} }, handleRemoveTab(targetName) { let tabs = this.tabList; let activeName = this.defTabKey; if (activeName === targetName) { tabs.forEach((tab, index) => { if (tab.close && tab.id === targetName) { let nextTab = tabs[index + 1] || tabs[index - 1]; if (nextTab) { activeName = nextTab.id; } } }); } this.defTabKey = activeName; tabs = tabs.filter((tab) => { return tab.close == false || tab.id !== targetName; }); console.log('handleRemoveTab') this.$set(this, "tabList", tabs); if (this.tabList.length == 0) { this.defTabKey = "tabPanel_home"; } }, handleRemoveAllTab() { let tabs = this.tabList; this.tabList = tabs.filter((tab) => { return !tab.close; }); let l = this.tabList.length; this.defTabKey = l ? this.tabList[l - 1].id : ""; }, handleRemoveLeftTab(name, index) { let tabs = this.tabList; let defTabKey = this.defTabKey; this.tabList = tabs.filter((tab, i) => { if (tab.id == defTabKey && i < index) { //当前的选中,是在关闭区内 defTabKey = name; } return tab.close == false || i >= index; }); this.defTabKey = defTabKey; }, handleRemoveRightTab(name, index) { let tabs = this.tabList; let defTabKey = this.defTabKey; this.tabList = tabs.filter((tab, i) => { if (tab.id == defTabKey && i > index) { //当前的选中,是在关闭区内 defTabKey = name; } return tab.close == false || i <= index; }); this.defTabKey = defTabKey; }, handleRemoveOtherTab(name, index) { let tabs = this.tabList; tabs = tabs.filter((tab, i) => { return tab.close == false || i == index; }); this.$set(this, "tabList", tabs); this.defTabKey = name; }, handleFullScreen() { this.$emit("onFullScreen"); // screenfull.toggle() }, }, }; </script> <style scoped> </style>
Show line notes below