vuex模块化及axios代理重新整理

This commit is contained in:
aixianling
2022-06-10 16:14:13 +08:00
parent 7cbe10ff64
commit 1218536e64
9 changed files with 174 additions and 158 deletions

View File

@@ -15,7 +15,8 @@
"src/common/util.js", "src/common/util.js",
"src/common/dict.js", "src/common/dict.js",
"src/common/monent.js", "src/common/monent.js",
"src/common/action.js", "src/common/modules.js",
"src/common/http.js",
"src/apps", "src/apps",
"src/saas" "src/saas"
], ],

View File

@@ -49,6 +49,7 @@ export default {
getApps() { getApps() {
this.setApps([]) this.setApps([])
this.$http.post("/node/wechatapps/list", null, { this.$http.post("/node/wechatapps/list", null, {
withoutToken: true,
params: {size: 999, type: 'wxwork'} params: {size: 999, type: 'wxwork'}
}).then(res => { }).then(res => {
if (res?.data) { if (res?.data) {

View File

@@ -1,23 +0,0 @@
const getVuex = () => {
return JSON.parse(uni.getStorageSync('vuex') || {})
}
const setVuex = vuex => {
uni.setStorageSync("vuex", JSON.stringify(vuex))
}
export default {
instance: null,
init(instance) {
this.instance = instance
},
getGridInfo() {
//获取登录着网格员信息
let vuex = getVuex()
this.instance?.post("/app/appgirdmemberinfo/checkLogOnUser").then(res => {
if (res?.data) {
let {girdId, girdMemberId, girdName, checkType: girdCheckType, appGirdInfo: gridInfo} = res.data
vuex.user = {...vuex.user, girdId, girdMemberId, girdName, girdCheckType, gridInfo}
setVuex(vuex)
}
})
}
}

View File

@@ -1,21 +1,15 @@
import axios from 'axios'
import store from '../store' import store from '../store'
import instance from './http'
const baseURL = process.env.NODE_ENV === "production" ? "/" :
sessionStorage.getItem("prj") == "saas" ? "/online" : "/lan"
let instance = axios.create({
baseURL,
timeout: 600000,
withCredentials: true,
})
instance.interceptors.request.use(config => { instance.interceptors.request.use(config => {
store.commit('initWaterMarker') store.commit('initWaterMarker')
config.baseURL = "/lan"
if (/\/node\//.test(config.url)) { if (/\/node\//.test(config.url)) {
config.baseURL = '/ns' config.baseURL = '/ns'
} else if (/AppCountryAlbum/.test(location.pathname) || config.module == 'AppCountryAlbum') { } else if (/AppCountryAlbum/.test(location.pathname) || config.module == 'AppCountryAlbum') {
config.baseURL = '/aca' config.baseURL = '/aca'
config.url = config.url.replace(/(app|auth|admin)\//, "api/") config.url = config.url.replace(/(app|auth|admin)\//, "api/")
} else if (/\/project\/beta\//.test(location.pathname) || store.state.config.corpid == 'ww2a667717a70164f1' || config.module == 'wangge') { } else if (/\/project\/beta\//.test(location.pathname) || config.module == 'wangge') {
config.baseURL = '/wangge' config.baseURL = '/wangge'
} else if (/\/project\/police\//.test(location.pathname) || config.module == 'hnjc') { } else if (/\/project\/police\//.test(location.pathname) || config.module == 'hnjc') {
config.baseURL = '/hnjc' config.baseURL = '/hnjc'
@@ -23,9 +17,6 @@ instance.interceptors.request.use(config => {
} else if (sessionStorage.getItem("prj") == "saas") { } else if (sessionStorage.getItem("prj") == "saas") {
config.baseURL = '/online' config.baseURL = '/online'
} }
if (!config.withoutToken && store.state.token) {
config.headers["Authorization"] = store.state.token
}
return config return config
}, err => { }, err => {
console.error(err) console.error(err)
@@ -45,7 +36,6 @@ instance.interceptors.response.use(res => {
duration: 2000, duration: 2000,
icon: 'none' icon: 'none'
}) })
return res.data return res.data
} else if (res.data.code == 401) { } else if (res.data.code == 401) {
store.commit("logout"); store.commit("logout");
@@ -61,7 +51,7 @@ instance.interceptors.response.use(res => {
}, err => { }, err => {
uni.hideLoading() uni.hideLoading()
console.error(err) console.error(err)
return Promise.reject(error) return Promise.reject(err)
}) })
export default instance export default instance

27
src/common/http.js Normal file
View File

@@ -0,0 +1,27 @@
import axios from 'axios'
const instance = axios.create({
timeout: 600000,
withCredentials: true,
})
const getToken = () => {
let vuex = uni.getStorageSync("vuex")
return !!vuex ? JSON.parse(vuex).token : null
}
const source = axios.CancelToken.source();
instance.interceptors.request.use(config => {
if (config.withoutToken) {
return config
} else if (getToken()) {
config.headers["Authorization"] = getToken()
} else {
config.cancelToken = source.token
source.cancel("用户未验证,取消请求:" + config.url)
}
return config
}, err => {
console.error(err)
return Promise.reject(err)
})
export default instance

118
src/common/modules.js Normal file
View File

@@ -0,0 +1,118 @@
import http from "./http";
import Vue from "vue";
export const user = {
state: () => ({}),
mutations: {
setUser(state, user) {
for (const key in user) {
Vue.set(state, key, user[key])
}
}
},
actions: {
getAccount({dispatch, commit}, config) {
//获取企业微信后台账号信息
return http.post("/admin/user/detail-phone", null, config).then(res => {
if (res?.code == 0) {
commit('setUser', res.data)
return Promise.all([dispatch('getGridInfo')])
}
})
},
getGridInfo({commit}) {
//获取登录着网格员信息
return http.post("/app/appgirdmemberinfo/checkLogOnUser").then(res => {
if (res?.data) {
let {girdId, girdMemberId, girdName, checkType: girdCheckType, appGirdInfo: gridInfo} = res.data
return commit("setUser", {girdId, girdMemberId, girdName, girdCheckType, gridInfo})
}
})
}
}
}
/**
* 水印方法
* */
export const waterMarker = {
mutations: {
initWaterMarker(state) {
const waterMarked = document.querySelector('#waterMarker')
if (!waterMarked && state.user?.name) {
const waterMarker = document.createElement('div')
waterMarker.id = 'waterMarker'
waterMarker.style.position = 'absolute'
waterMarker.style.display = 'flex'
waterMarker.style.flexWrap = 'wrap'
waterMarker.style.overflow = 'hidden'
waterMarker.style.justifyContent = 'space-between'
waterMarker.style.alignContent = 'flex-start'
waterMarker.style.zIndex = '2'
waterMarker.style.top = '0'
waterMarker.style.color = 'rgba(153,153,153,.2)'
waterMarker.style.width = '100%'
waterMarker.style.height = '100%'
waterMarker.style.pointerEvents = 'none'
for (let i = 0; i < 200; i++) {
const markerItem = document.createElement('div')
markerItem.style.fontSize = '14px'
markerItem.style.padding = '30px'
markerItem.style.height = '80px'
markerItem.style.transform = 'rotate(-20deg)'
markerItem.style.flexShrink = '0'
markerItem.innerText = state.user?.name + state.user?.phone?.slice(-4) || "未授权"
waterMarker.appendChild(markerItem)
}
document.querySelector('uni-page-body')?.appendChild(waterMarker)
}
// canvas 方案
// const HiDPICanvas = (w, h, ratio) => {
// const PIXEL_RATIO = () => {
// const c = document.createElement("canvas"),
// ctx = c.getContext("2d"),
// dpr = window.devicePixelRatio || 1,
// bsr = ctx['webkitBackingStorePixelRatio'] ||
// ctx['mozBackingStorePixelRatio'] ||
// ctx['msBackingStorePixelRatio'] ||
// ctx['oBackingStorePixelRatio'] ||
// ctx['backingStorePixelRatio'] || 1;
//
// return dpr / bsr;
// }
// if (!ratio) {
// ratio = PIXEL_RATIO();
// }
// const can = document.createElement("canvas");
// can.width = w * ratio;
// can.height = h * ratio;
// can.style.width = w + "px";
// can.style.height = h + "px";
// can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
// return can
// }
// if (!waterMarked && state.user?.name) {
// const canvas = HiDPICanvas(100, 40)
// canvas.style.display = 'none';
// let ctx = canvas.getContext("2d")
// ctx.rotate(-20 * Math.PI / 180);
// ctx.fillStyle = 'rgba(153,153,153,.3)';
// ctx.textAlign = 'left';
// ctx.textBaseline = 'middle';
// ctx.font = "lighter 7px 'Microsoft YaHei UI',sans-serif"
// ctx.fillText(state.user?.name + state.user?.phone?.slice(-4) || "未授权", 0, 30);
// const waterMarker = document.createElement('div')
// if (waterMarker) {
// waterMarker.id = 'waterMarker'
// waterMarker.style.position = 'absolute'
// waterMarker.style.zIndex = '2'
// waterMarker.style.top = '0'
// waterMarker.style.width = '100%'
// waterMarker.style.height = '100%'
// waterMarker.style.pointerEvents = 'none'
// waterMarker.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")"
// document.querySelector('uni-page-body').appendChild(waterMarker)
// }
// }
}
}
}

View File

@@ -1,7 +1,6 @@
import dict from "./dict"; import dict from "./dict";
import dayjs from './monent'; import dayjs from './monent';
import qs from 'query-string' import qs from 'query-string'
import action from './action'
const confirm = (content, title, config) => { const confirm = (content, title, config) => {
let ops = {content} let ops = {content}
@@ -297,6 +296,5 @@ export default {
idCardNoUtil, idCardNoUtil,
qs, qs,
permissions, permissions,
copy, copy
action
} }

View File

@@ -28,9 +28,8 @@ Vue.prototype.$dayjs = dayjs
Vue.prototype.$cdn = 'https://cdn.cunwuyun.cn/dvcp/h5/'; Vue.prototype.$cdn = 'https://cdn.cunwuyun.cn/dvcp/h5/';
Object.keys(utils).map((e) => (Vue.prototype['$' + e] = utils[e])); Object.keys(utils).map((e) => (Vue.prototype['$' + e] = utils[e]));
utils.dict.init({instance: axios}) utils.dict.init({instance: axios})
utils.action.init(axios)
App.mpType = 'app'; App.mpType = 'app';
// process.env.NODE_ENV == 'development' && new VConsole(); process.env.NODE_ENV == 'development' && new VConsole();
const app = new Vue({ const app = new Vue({
store, store,
...App ...App

View File

@@ -3,7 +3,7 @@ import Vuex from 'vuex'
import perState from 'vuex-persistedstate' import perState from 'vuex-persistedstate'
import http from '../common/axios' import http from '../common/axios'
import CryptoJS from '../utils/crypto-js' import CryptoJS from '../utils/crypto-js'
import action from "../common/action"; import {user, waterMarker} from "../common/modules";
Vue.use(Vuex) Vue.use(Vuex)
let agentSignURL = "", apiList = [] let agentSignURL = "", apiList = []
@@ -11,7 +11,6 @@ const store = new Vuex.Store({
state: { state: {
token: "", token: "",
openUser: {}, openUser: {},
user: {},
config: {}, config: {},
apps: [] apps: []
}, },
@@ -26,9 +25,6 @@ const store = new Vuex.Store({
state.token = "" state.token = ""
state.openUser = {} state.openUser = {}
}, },
setUser(state, user) {
state.user = user
},
setOpenUser(state, user) { setOpenUser(state, user) {
state.openUser = user state.openUser = user
}, },
@@ -79,87 +75,7 @@ const store = new Vuex.Store({
}) })
} }
}, },
initWaterMarker(state) {
const waterMarked = document.querySelector('#waterMarker')
if (!waterMarked && state.user?.name) {
const waterMarker = document.createElement('div')
for (let i = 0; i < 200; i++) {
let markerItem = document.createElement('div')
markerItem.style.fontSize = '14px'
markerItem.style.padding = '30px'
markerItem.style.height = '80px'
markerItem.style.transform = 'rotate(-20deg)'
markerItem.style.flexShrink = '0'
markerItem.innerText = state.user?.name + state.user?.phone?.slice(-4) || "未授权"
waterMarker.appendChild(markerItem)
}
if (waterMarker) {
waterMarker.id = 'waterMarker'
waterMarker.style.position = 'absolute'
waterMarker.style.display = 'flex'
waterMarker.style.flexWrap = 'wrap'
waterMarker.style.overflow = 'hidden'
waterMarker.style.justifyContent = 'space-between'
waterMarker.style.alignContent = 'flex-start'
waterMarker.style.zIndex = '2'
waterMarker.style.top = '0'
waterMarker.style.color = 'rgba(153,153,153,.2)'
waterMarker.style.width = '100%'
waterMarker.style.height = '100%'
waterMarker.style.pointerEvents = 'none'
document.querySelector('uni-page-body')?.appendChild(waterMarker)
}
}
// canvas 方案
// const HiDPICanvas = (w, h, ratio) => {
// const PIXEL_RATIO = () => {
// const c = document.createElement("canvas"),
// ctx = c.getContext("2d"),
// dpr = window.devicePixelRatio || 1,
// bsr = ctx['webkitBackingStorePixelRatio'] ||
// ctx['mozBackingStorePixelRatio'] ||
// ctx['msBackingStorePixelRatio'] ||
// ctx['oBackingStorePixelRatio'] ||
// ctx['backingStorePixelRatio'] || 1;
//
// return dpr / bsr;
// }
// if (!ratio) {
// ratio = PIXEL_RATIO();
// }
// const can = document.createElement("canvas");
// can.width = w * ratio;
// can.height = h * ratio;
// can.style.width = w + "px";
// can.style.height = h + "px";
// can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
// return can
// }
// if (!waterMarked && state.user?.name) {
// const canvas = HiDPICanvas(100, 40)
// canvas.style.display = 'none';
// let ctx = canvas.getContext("2d")
// ctx.rotate(-20 * Math.PI / 180);
// ctx.fillStyle = 'rgba(153,153,153,.3)';
// ctx.textAlign = 'left';
// ctx.textBaseline = 'middle';
// ctx.font = "lighter 7px 'Microsoft YaHei UI',sans-serif"
// ctx.fillText(state.user?.name + state.user?.phone?.slice(-4) || "未授权", 0, 30);
// const waterMarker = document.createElement('div')
// if (waterMarker) {
// waterMarker.id = 'waterMarker'
// waterMarker.style.position = 'absolute'
// waterMarker.style.zIndex = '2'
// waterMarker.style.top = '0'
// waterMarker.style.width = '100%'
// waterMarker.style.height = '100%'
// waterMarker.style.pointerEvents = 'none'
// waterMarker.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")"
// document.querySelector('uni-page-body').appendChild(waterMarker)
// }
// }
}
}, },
actions: { actions: {
getToken(state, params) { getToken(state, params) {
@@ -179,8 +95,7 @@ const store = new Vuex.Store({
} }
} }
let {module} = params let {module} = params
return new Promise((resolve, reject) => { return http.post("/auth/oauth/token", null, {
http.post("/auth/oauth/token", null, {
withoutToken: true, withoutToken: true,
module, module,
params: { params: {
@@ -193,13 +108,10 @@ const store = new Vuex.Store({
}).then(res => { }).then(res => {
if (res?.access_token) { if (res?.access_token) {
state.commit("login", [res?.token_type, res?.access_token].join(" ").trim()) state.commit("login", [res?.token_type, res?.access_token].join(" ").trim())
module != 'AppCountryAlbum' && state.dispatch("getAccount", {module}) return module != 'AppCountryAlbum' && state.dispatch("getAccount", {module})
resolve()
} }
}).catch(err => { }).catch(err => {
uni.showToast({title: err, icon: 'none'}) uni.showToast({title: err, icon: 'none'})
reject()
})
}) })
}, },
getCode(store, url) { getCode(store, url) {
@@ -211,15 +123,6 @@ const store = new Vuex.Store({
}) })
} }
}, },
getAccount(state, config) {
//获取企业微信后台账号信息
return http.post("/admin/user/detail-phone", null, config).then(res => {
if (res?.code == 0) {
state.commit('setUser', res.data)
action.getGridInfo()
}
})
},
getUserInfo(state, code) { getUserInfo(state, code) {
if (code) { if (code) {
return http.post("/app/wxcp/portal/getUserInfo", null, { return http.post("/app/wxcp/portal/getUserInfo", null, {
@@ -249,6 +152,7 @@ const store = new Vuex.Store({
params = {...params, corpId: "ww596787bb70f08288"} params = {...params, corpId: "ww596787bb70f08288"}
action = "/app/wxcptp/portal/agentSign" action = "/app/wxcptp/portal/agentSign"
} }
state.commit("getConfig", {})
return http.post(action, null, { return http.post(action, null, {
withoutToken: true, withoutToken: true,
params: {...params, url} params: {...params, url}
@@ -389,6 +293,7 @@ const store = new Vuex.Store({
return null return null
} }
}, },
modules: {user, waterMarker},
plugins: [perState({ plugins: [perState({
storage: { storage: {
getItem: key => uni.getStorageSync(key), getItem: key => uni.getStorageSync(key),