Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 接口请求优化以及修复attrs问题 #281

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions web/src/management/api/space.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios from './base'

import memorize from '@/management/utils/memorize'
// 空间
export const createSpace = ({ name, description, members }: any) => {
return axios.post('/workspace', { name, description, members })
Expand Down Expand Up @@ -29,10 +29,11 @@ export const getUserList = (username: string) => {
})
}

// 协作权限列表
// 获取协作权限下拉框枚举
export const getPermissionList = () => {
return axios.get('collaborator/getPermissionList')
}
export const getPermissionListMemorize = memorize(getPermissionList)

export const saveCollaborator = ({ surveyId, collaborators }: any) => {
return axios.post('collaborator/batchSave', {
Expand Down Expand Up @@ -73,3 +74,4 @@ export const getCollaboratorPermissions = (surveyId: string) => {
}
})
}
export const getCollaboratorPermissionsMemorize = memorize(getCollaboratorPermissions)
14 changes: 7 additions & 7 deletions web/src/management/components/LeftMenu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ref, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
const route = useRoute()
Expand Down Expand Up @@ -58,18 +58,18 @@ const tabArr = [
}
]
const tabs = ref([])
onMounted(async () => {
await store.dispatch('fetchCooperPermissions', route.params.id)
watch(() => store.state.cooperPermissions, (newVal) => {
tabs.value = []
// 如果有问卷管理权限,则加入问卷编辑和投放菜单
if (store.state.cooperPermissions.includes(SurveyPermissions.SurveyManage)) {
if (newVal.includes(SurveyPermissions.SurveyManage)) {
tabs.value.push(tabArr[0])
tabs.value.push(tabArr[1])
}
}
// 如果有数据分析权限,则加入数据分析菜单
if (store.state.cooperPermissions.includes(SurveyPermissions.DataManage)) {
if (newVal.includes(SurveyPermissions.DataManage)) {
tabs.value.push(tabArr[2])
}
})
}, { immediate: true })
</script>
<style lang="scss" scoped>
.nav {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
</div>
</template>
<script setup lang="ts">
const handleNavigateHome = () => window.open('/survey', '_self')
import { useRouter } from 'vue-router'
const router = useRouter()
const handleNavigateHome = () => {
router.push({
name: 'survey'
})
}
</script>
<style lang="scss" scoped>
.back-btn {
Expand Down
4 changes: 2 additions & 2 deletions web/src/management/pages/list/components/CooperModify.vue
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import { computed, ref, shallowRef, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import MemberSelect from './MemberSelect.vue'
import { getPermissionList, getCollaborator, saveCollaborator } from '@/management/api/space'
import { getPermissionListMemorize, getCollaborator, saveCollaborator } from '@/management/api/space'
import { type IMember, SurveyPermissions } from '@/management/utils/types/workSpace'
import { CODE_MAP } from '@/management/api/base'
const emit = defineEmits(['on-close-codify', 'onFocus', 'change', 'blur'])
Expand All @@ -64,7 +64,7 @@ const formTitle = ref('协作管理')

const cooperOptions = ref([])
onMounted(async () => {
const res: any = await getPermissionList()
const res: any = await getPermissionListMemorize()
if (res.code === CODE_MAP.SUCCESS) {
cooperOptions.value = res.data.map((item: any) => {
return {
Expand Down
5 changes: 1 addition & 4 deletions web/src/management/pages/list/components/SpaceList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
row-class-name="tableview-row"
cell-class-name="tableview-cell"
style="width: 100%"
@row-click="onRowClick"
>
<el-table-column column-key="space" width="20" />
<el-table-column
Expand Down Expand Up @@ -98,9 +97,7 @@ const isAdmin = (id: string) => {
UserRole.Admin
)
}
const onRowClick = () => {
console.log('onRowClick')
}

const handleModify = async (id: string) => {
await store.dispatch('list/getSpaceDetail', id)
modifyType.value = 'edit'
Expand Down
97 changes: 50 additions & 47 deletions web/src/management/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router'
import { createRouter, createWebHistory, type RouteLocationNormalized, type NavigationGuardNext } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useStore } from 'vuex'
import { useStore, type Store } from 'vuex'
import { SurveyPermissions } from '@/management/utils/types/workSpace'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
Expand All @@ -23,7 +23,7 @@ const routes: RouteRecordRaw[] = [
path: '/survey/:id/edit',
meta: {
needLogin: true,
premissions: [SurveyPermissions.SurveyManage]
permissions: [SurveyPermissions.SurveyManage]
},
name: 'QuestionEdit',
component: () => import('../pages/edit/index.vue'),
Expand Down Expand Up @@ -94,7 +94,7 @@ const routes: RouteRecordRaw[] = [
name: 'analysisPage',
meta: {
needLogin: true,
premissions: [SurveyPermissions.DataManage]
permissions: [SurveyPermissions.DataManage]
},
component: () => import('../pages/analysis/AnalysisPage.vue')
},
Expand All @@ -103,7 +103,7 @@ const routes: RouteRecordRaw[] = [
name: 'publish',
meta: {
needLogin: true,
premissions: [SurveyPermissions.SurveyManage]
permissions: [SurveyPermissions.SurveyManage]
},
component: () => import('../pages/publish/PublishPage.vue')
},
Expand Down Expand Up @@ -132,57 +132,60 @@ const router = createRouter({
})

router.beforeEach(async (to, from, next) => {
const store = useStore()
const store = useStore();
// 初始化用户信息
if (!store.state.user?.initialized) {
store?.dispatch('user/init')
await store.dispatch('user/init');
}
// 更新页面标题
if (to.meta.title) {
document.title = to.meta.title as string
document.title = to.meta.title as string;
}

if (to.meta.needLogin) {
if (store?.state?.user?.hasLogined) {
if (to.meta.premissions) {
const params = to.params
await store.dispatch('fetchCooperPermissions', params.id)
if (
(to.meta.premissions as []).some((permission) =>
store.state?.cooperPermissions?.includes(permission)
)
) {
next()
} else {
ElMessage.warning('您没有该问卷的相关协作权限')
next({
name: 'survey'
})
}
await handleLoginGuard(to, from, next, store);
} else {
next();
}
});

async function handleLoginGuard(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext, store: Store<any>) {
if (store.state.user?.hasLogined) {
await handlePermissionsGuard(to, from, next, store);
} else {
next({
name: 'login',
query: { redirect: encodeURIComponent(to.path) },
});
}
}

async function handlePermissionsGuard(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext, store: Store<any>) {
const currSurveyId = to?.params?.id || ''
const prevSurveyId = from?.params?.id || ''
// 如果跳转页面不存在surveyId 或者不需要页面权限,则直接跳转
if (!to.meta.permissions || !currSurveyId) {
next()
} else {
// 如果跳转编辑页面,且跳转页面和上一页的surveyId不同,判断是否有对应页面权限
if (currSurveyId !== prevSurveyId) {
await store.dispatch('fetchCooperPermissions', currSurveyId)
if (hasRequiredPermissions(to.meta.permissions as string[], store.state.cooperPermissions)) {
next();
} else {
next()
ElMessage.warning('您没有该问卷的相关协作权限');
next({ name: 'survey' });
}
} else {
next({
name: 'login',
query: {
redirect: encodeURIComponent(to.path)
}
})
next();
}
} else {
next()
}
})
}

function hasRequiredPermissions(requiredPermissions: string[], userPermissions: string[]) {
return requiredPermissions.some(permission => userPermissions.includes(permission));
}



// router.afterEach(async (to, from) => {
// const store = useStore()
// if (to.meta.premissions) {
// const params = to.params
// await store.dispatch('fetchCooperPermissions', params.id)
// if (!(to.meta.premissions as []).some((permission) => store.state?.cooperPermissions?.includes(permission))) {
// ElMessage.warning('您没有该问卷的相关协作权限')
// router.push({
// name: 'survey'
// })
// }
// }
// })
export default router
5 changes: 2 additions & 3 deletions web/src/management/store/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getBannerData } from '@/management/api/skin.js'
import { getCollaboratorPermissions } from '@/management/api/space.ts'
import { getCollaboratorPermissionsMemorize } from '@/management/api/space.ts'
import { CODE_MAP } from '../api/base'

export default {
Expand All @@ -13,8 +13,7 @@ export default {
}
},
async fetchCooperPermissions({ commit }, id) {
const res = await getCollaboratorPermissions(id)
console.log(res.data)
const res = await getCollaboratorPermissionsMemorize(id)
if (res.code === CODE_MAP.SUCCESS) {
commit('setCooperPermissions', res.data.permissions)
}
Expand Down
41 changes: 41 additions & 0 deletions web/src/management/utils/memorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const serialize = (obj: any): string => {
if (obj == null) {
return ''
} else if (Array.isArray(obj)) {
const items = obj.map((item) => serialize(item))
return `[${items.join(',')}]`
} else if (isPlainObject(obj)) {
const keys = Object.keys(obj)
keys.sort()
const items = keys.map((key) => `${key}=${serialize(obj[key])}`)
return `{${items.join('&')}}`
} else if (typeof obj === 'object' && typeof obj.valueOf === 'function') {
return serialize(obj.valueOf())
} else {
return obj + ''
}
}

function isPlainObject(obj: Object) {
const prototype = Object.getPrototypeOf(obj)
return obj && typeof obj === 'object' && (prototype === null || prototype === Object.prototype)
}

/*
记忆函数:通过缓存函数的调用结果,
使用场景:
1. 相对固定的静态枚举数据,比如下拉框的数据,可以在初次请求的时候缓存在 js 对象中,避免每次请求服务器
2. 输入参数决定输出的函数,利用函数缓存能避免重复计算
*/
export default function memorize(fn: Function) {
const results: any = {}

return (...args: any) => {
const key = serialize(args)
if (!(key in results)) {
// @ts-ignore
results[key] = fn.apply(this, args)
}
return results[key]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ const emit = defineEmits(['addOther', 'optionChange', 'change'])
const moduleConfig = inject('moduleConfig')
const optionConfigVisible = ref(false)
const openOptionConfig = () => {
console.log('open')
optionConfigVisible.value = true
}

Expand Down
3 changes: 0 additions & 3 deletions web/src/render/components/MaterialGroup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
<div v-for="item in renderData" :key="item.field">
<QuestionWrapper
class="gap"
v-bind="$attrs"
:moduleConfig="item"
:qIndex="item.qIndex"
:indexNumber="item.indexNumber"
:showTitle="true"
@change="handleChange"
></QuestionWrapper>
</div>
Expand Down
1 change: 0 additions & 1 deletion web/src/render/components/QuestionWrapper.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<template>
<QuestionRuleContainer
v-if="visible"
v-bind="$attrs"
:moduleConfig="questionConfig"
:indexNumber="indexNumber"
:showTitle="true"
Expand Down
1 change: 0 additions & 1 deletion web/src/render/pages/IndexPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ const submitSurver = async () => {
}
try {
const params = normalizationRequestBody()
console.log(params)
const res: any = await submitForm(params)
if (res.code === 200) {
store.commit('setRouter', 'successPage')
Expand Down
1 change: 0 additions & 1 deletion web/src/render/store/getters.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export default {
const questionArr = []

item.forEach((questionKey) => {
console.log('题目重新计算')
const question = { ...questionData[questionKey] }
// 开启显示序号
if (question.showIndex) {
Expand Down