feature: 搭建端全局模块下的变量迁移pinia-edit模块 (#336)

* fix: 搭建端的pinia迁移完成

* fix:删除store
This commit is contained in:
dayou 2024-07-15 11:23:09 +08:00 committed by GitHub
parent 5a8fab4e4b
commit f08c8bcd2a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 43 additions and 677 deletions

View File

@ -27,12 +27,12 @@
<script setup>
import { ref, watch } from 'vue'
import { useStore } from 'vuex'
import { useEditStore } from '@/management/stores/edit'
import { useRoute } from 'vue-router'
const route = useRoute()
import LogoIcon from './LogoIcon.vue'
import { SurveyPermissions } from '@/management/utils/types/workSpace.ts'
const store = useStore()
const editStore = useEditStore()
const tabArr = [
{
@ -59,7 +59,7 @@ const tabArr = [
]
const tabs = ref([])
watch(
() => store.state.cooperPermissions,
() => editStore.cooperPermissions,
(newVal) => {
tabs.value = []
//

View File

@ -1,5 +1,4 @@
import { createApp } from 'vue'
import store from './store'
import { createPinia } from 'pinia'
import plainText from './directive/plainText'
import safeHtml from './directive/safeHtml'
@ -10,7 +9,6 @@ import router from './router'
const pinia = createPinia()
const app = createApp(App)
app.use(store)
app.use(pinia)
app.use(router)

View File

@ -32,11 +32,10 @@ import { useEditStore } from '@/management/stores/edit'
import skinPresets from '@/management/config/skinPresets.js'
const store = useStore()
const editStore = useEditStore()
const { changeThemePreset } = editStore
const groupName = ref<string>('temp')
const bannerList = computed(() => store?.state?.bannerList || [])
const bannerList = computed(() => editStore.bannerList || [])
const groupList = computed(() =>
Object.keys(bannerList.value).map((key) => ({
label: bannerList.value[key].name,

View File

@ -13,17 +13,17 @@
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
import { useStore } from 'vuex'
import { useEditStore } from '@/management/stores/edit'
import CommonTemplate from '../../components/CommonTemplate.vue'
import CatalogPanel from '../../modules/settingModule/skin/CatalogPanel.vue'
import PreviewPanel from '../../modules/settingModule/skin/PreviewPanel.vue'
import SetterPanel from '../../modules/settingModule/skin/SetterPanel.vue'
const store = useStore()
const editStore = useEditStore()
onMounted(() => {
store.dispatch('getBannerData')
editStore.fetchBannerData()
})
</script>
<style lang="scss" scoped>

View File

@ -11,6 +11,7 @@ import { analysisTypeMap } from '@/management/config/analysisConfig'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import { useUserStore } from '@/management/stores/user'
import { useEditStore } from '@/management/stores/edit'
const routes: RouteRecordRaw[] = [
{
@ -162,7 +163,6 @@ const router = createRouter({
})
router.beforeEach(async (to, from, next) => {
const store = useStore()
const userStore = useUserStore()
// 初始化用户信息
if (!userStore?.initialized) {
@ -174,7 +174,7 @@ router.beforeEach(async (to, from, next) => {
}
if (to.meta.needLogin) {
await handleLoginGuard(to, from, next, store)
await handleLoginGuard(to, from, next)
} else {
next()
}
@ -183,12 +183,11 @@ router.beforeEach(async (to, from, next) => {
async function handleLoginGuard(
to: RouteLocationNormalized,
from: RouteLocationNormalized,
next: NavigationGuardNext,
store: Store<any>
next: NavigationGuardNext
) {
const userStore = useUserStore()
if (userStore?.hasLogined) {
await handlePermissionsGuard(to, from, next, store)
await handlePermissionsGuard(to, from, next)
} else {
next({
name: 'login',
@ -200,9 +199,9 @@ async function handleLoginGuard(
async function handlePermissionsGuard(
to: RouteLocationNormalized,
from: RouteLocationNormalized,
next: NavigationGuardNext,
store: Store<any>
next: NavigationGuardNext
) {
const editStore = useEditStore()
const currSurveyId = to?.params?.id || ''
const prevSurveyId = from?.params?.id || ''
// 如果跳转页面不存在surveyId 或者不需要页面权限,则直接跳转
@ -211,8 +210,8 @@ async function handlePermissionsGuard(
} else {
// 如果跳转编辑页面且跳转页面和上一页的surveyId不同判断是否有对应页面权限
if (currSurveyId !== prevSurveyId) {
await store.dispatch('fetchCooperPermissions', currSurveyId)
if (hasRequiredPermissions(to.meta.permissions as string[], store.state.cooperPermissions)) {
await editStore.fetchCooperPermissions(currSurveyId as string)
if (hasRequiredPermissions(to.meta.permissions as string[], editStore.cooperPermissions)) {
next()
} else {
ElMessage.warning('您没有该问卷的相关协作权限')

View File

@ -1,21 +0,0 @@
import { getBannerData } from '@/management/api/skin.js'
import { getCollaboratorPermissions } from '@/management/api/space.ts'
import { CODE_MAP } from '../api/base'
export default {
async getBannerData({ state, commit }) {
if (state.bannerList && state.bannerList.length > 0) {
return
}
const res = await getBannerData()
if (res.code === 200) {
commit('setBannerList', res.data)
}
},
async fetchCooperPermissions({ commit }, id) {
const res = await getCollaboratorPermissions(id)
if (res.code === CODE_MAP.SUCCESS) {
commit('setCooperPermissions', res.data.permissions)
}
}
}

View File

@ -1,72 +0,0 @@
import { getNewField } from '@/management/utils'
import { cloneDeep as _cloneDeep, get as _get } from 'lodash-es'
import { getSurveyById } from '@/management/api/survey'
export default {
async init({ state, dispatch }) {
const metaData = _get(state, 'schema.metaData')
if (!metaData || metaData._id !== state.surveyId) {
await dispatch('getSchemaFromRemote')
}
dispatch('resetState')
},
async getSchemaFromRemote({ commit, state }) {
const res = await getSurveyById(state.surveyId)
if (res.code === 200) {
const metaData = res.data.surveyMetaRes
document.title = metaData.title
const {
bannerConf,
bottomConf,
skinConf,
baseConf,
submitConf,
dataConf,
logicConf = {}
} = res.data.surveyConfRes.code
commit('initSchema', {
metaData,
codeData: {
bannerConf,
bottomConf,
skinConf,
baseConf,
submitConf,
questionDataList: dataConf.dataList,
logicConf
}
})
} else {
throw new Error(res.errmsg || '问卷不存在')
}
},
resetState({ commit }) {
commit('setCurrentEditOne', null)
commit('changeStatusPreview', { type: 'Success' })
},
// 复制题目到当前题目后
copyQuestion({ commit, state }, { index }) {
const newQuestion = _cloneDeep(state.schema.questionDataList[index])
newQuestion.field = getNewField(state.schema.questionDataList.map((item) => item.field))
commit('addQuestion', { question: newQuestion, index })
},
addQuestion({ commit }, { question, index }) {
commit('addQuestion', { question, index })
commit('updateSchemaUpdateTime', Date.now())
},
deleteQuestion({ commit }, { index }) {
commit('deleteQuestion', { index })
commit('updateSchemaUpdateTime', Date.now())
},
moveQuestion({ commit }, { index, range }) {
commit('moveQuestion', { index, range })
commit('updateSchemaUpdateTime', Date.now())
},
changeSchema({ commit }, { key, value }) {
commit('changeSchema', { key, value })
commit('updateSchemaUpdateTime', Date.now())
},
changeThemePreset({ commit }, presets) {
commit('changeThemePreset', presets)
}
}

View File

@ -1,71 +0,0 @@
import submitFormConfig from '@/management/config/setterConfig/submitConfig'
import questionLoader from '@/materials/questions/questionLoader'
const innerMetaConfig = {
submit: {
title: '提交配置',
formConfig: submitFormConfig
}
}
export default {
moduleConfig(state) {
const currentEditOne = state.currentEditOne
if (currentEditOne === null) {
return null
}
if (currentEditOne === 'banner' || currentEditOne === 'mainTitle') {
return state?.schema?.bannerConf
} else if (currentEditOne === 'submit') {
return state?.schema?.submitConf
} else if (currentEditOne === 'logo') {
return state?.schema?.bottomConf
} else if (!Number.isNaN(currentEditOne)) {
return state?.schema?.questionDataList?.[currentEditOne]
} else {
return null
}
},
formConfigList(state, getters) {
const currentEditOne = state.currentEditOne
if (currentEditOne === null) {
return null
}
return getters?.currentEditMeta?.formConfig || []
},
currentEditMeta(state) {
const currentEditOne = state.currentEditOne
if (currentEditOne === null) {
return null
} else if (innerMetaConfig[currentEditOne]) {
return innerMetaConfig[currentEditOne]
} else {
const questionType = state.schema?.questionDataList?.[currentEditOne]?.type
return questionLoader.getMeta(questionType)
}
},
currentEditKey(state) {
const currentEditOne = state.currentEditOne
if (currentEditOne === null) {
return null
}
let key = ''
switch (currentEditOne) {
case 'banner':
case 'mainTitle':
key = 'bannerConf'
break
case 'submit':
key = 'submitConf'
break
case 'logo':
key = 'bottomConf'
break
default:
key = `questionDataList.${currentEditOne}`
}
return key
}
}

View File

@ -1,12 +0,0 @@
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
export default {
namespaced: true,
state,
actions,
getters,
mutations
}

View File

@ -1,68 +0,0 @@
import { set as _set, merge as _merge } from 'lodash-es'
export default {
setCurrentEditOne(state, data) {
state.currentEditOne = data
},
changeStatusPreview(state, { type }) {
state.currentEditStatus = type
},
updateSchemaUpdateTime(state) {
state.schemaUpdateTime = Date.now()
},
initSchema(state, { metaData, codeData }) {
state.schema.metaData = metaData
state.schema.bannerConf = _merge({}, state.schema.bannerConf, codeData.bannerConf)
state.schema.bottomConf = _merge({}, state.schema.bottomConf, codeData.bottomConf)
state.schema.skinConf = _merge({}, state.schema.skinConf, codeData.skinConf)
state.schema.baseConf = _merge({}, state.schema.baseConf, codeData.baseConf)
state.schema.submitConf = _merge({}, state.schema.submitConf, codeData.submitConf)
state.schema.questionDataList = codeData.questionDataList || []
state.schema.logicConf = codeData.logicConf
},
setSurveyId(state, data) {
state.surveyId = data
},
addQuestion(state, { question, index }) {
state.schema.questionDataList.splice(index, 0, question)
},
deleteQuestion(state, { index }) {
state.schema.questionDataList.splice(index, 1)
},
moveQuestion(state, { index, range }) {
let start, end
if (range < 0) {
// 向上移动
start = index + range
end = index
} else if (range > 0) {
// 向下移动
start = index + 1
end = index + range + 1
} else {
// 无变化
return
}
const currentData = state.schema.questionDataList[index]
// 新位置和老位置之间所有的题目
const comparedList = state.schema.questionDataList.slice(start, end)
if (range < 0) {
// 向上移动
state.schema.questionDataList.splice(index + range, 1 - range, currentData, ...comparedList)
} else if (range > 0) {
// 向下移动
state.schema.questionDataList.splice(index, range + 1, ...comparedList, currentData)
}
},
changeSchema(state, { key, value }) {
_set(state.schema, key, value)
},
changeThemePreset(state, presets) {
Object.keys(presets).forEach((key) => {
_set(state.schema, key, presets[key])
})
},
setQuestionDataList(state, data) {
state.schema.questionDataList = data
}
}

View File

@ -1,60 +0,0 @@
export default {
currentEditOne: null,
currentEditStatus: 'Success',
schemaUpdateTime: Date.now(),
surveyId: '', // url上取的surveyId
schema: {
metaData: null,
bannerConf: {
titleConfig: {
mainTitle: '<h3 style="text-align: center">欢迎填写问卷</h3>',
subTitle: `<p>为了给您提供更好的服务,希望您能抽出几分钟时间,将您的感受和建议告诉我们,<span style="color: rgb(204, 0, 0)">期待您的参与!</span></p>`,
applyTitle: ''
},
bannerConfig: {
bgImage: '',
bgImageAllowJump: false,
bgImageJumpLink: '',
videoLink: '',
postImg: ''
}
},
bottomConf: {
logoImage: '',
logoImageWidth: '28%'
},
skinConf: {
backgroundConf: {
color: '#fff'
},
themeConf: {
color: '#ffa600'
},
contentConf: {
opacity: 100
}
},
baseConf: {
begTime: '',
endTime: '',
language: 'chinese',
showVoteProcess: 'allow',
tLimit: 0,
answerBegTime: '',
answerEndTime: '',
answerLimitTime: 0
},
submitConf: {
submitTitle: '',
msgContent: {},
confirmAgain: {
is_again: true
},
link: ''
},
questionDataList: [],
logicConf: {
showLogicConf: []
}
}
}

View File

@ -1,19 +0,0 @@
import { createStore } from 'vuex'
import edit from './edit'
// import user from './user'
// import list from './list'
import actions from './actions'
import mutations from './mutations'
import state from './state'
export default createStore({
state,
getters: {},
mutations,
actions,
modules: {
edit
// user,
// list
}
})

View File

@ -1,258 +0,0 @@
import {
createSpace,
getSpaceList,
getSpaceDetail,
updateSpace,
deleteSpace
} from '@/management/api/space'
import { CODE_MAP } from '@/management/api/base'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import { getSurveyList as surveyList } from '@/management/api/survey'
import { set } from 'lodash-es'
import { SpaceType } from '@/management/utils/types/workSpace'
export default {
namespaced: true,
state: {
// 空间管理
spaceMenus: [
{
icon: 'icon-wodekongjian',
name: '我的空间',
id: SpaceType.Personal
},
{
icon: 'icon-tuanduikongjian',
name: '团队空间',
id: SpaceType.Group,
children: [
// {
// name: '小桔问卷调研团队',
// id: 'xxxx',
// }
]
}
],
spaceType: SpaceType.Personal,
workSpaceId: '',
spaceDetail: null,
workSpaceList: [],
// 列表管理
surveyList: [],
surveyTotal: 0,
searchVal: '',
selectValueMap: {
surveyType: '',
'curStatus.status': ''
},
buttonValueMap: {
'curStatus.date': '',
createDate: -1
}
},
getters: {
listFilter(state) {
return [
{
comparator: '',
condition: [
{
field: 'title',
value: state.searchVal,
comparator: '$regex'
}
]
},
{
comparator: '',
condition: [
{
field: 'curStatus.status',
value: state.selectValueMap['curStatus.status']
}
]
},
{
comparator: '',
condition: [
{
field: 'surveyType',
value: state.selectValueMap.surveyType
}
]
}
]
},
listOrder(state) {
const { buttonValueMap } = state
return Object.entries(buttonValueMap)
.filter(([, effectValue]) => effectValue)
.reduce((prev, item) => {
const [effectKey, effectValue] = item
prev.push({ field: effectKey, value: effectValue })
return prev
}, [])
}
},
mutations: {
updateSpaceMenus(state, workSpace) {
// 更新空间列表下的团队空间
set(state, 'spaceMenus[1].children', workSpace)
},
changeSpaceType(state, spaceType) {
state.spaceType = spaceType
},
changeWorkSpace(state, workSpaceId) {
// 切换空间清除筛选条件
this.commit('list/resetSelectValueMap')
this.commit('list/resetButtonValueMap')
this.commit('list/setSearchVal', '')
state.workSpaceId = workSpaceId
},
setSpaceDetail(state, data) {
state.spaceDetail = data
},
setWorkSpaceList(state, data) {
state.workSpaceList = data
},
setSurveyList(state, list) {
state.surveyList = list
},
setSurveyTotal(state, total) {
state.surveyTotal = total
},
setSearchVal(state, data) {
state.searchVal = data
},
resetSelectValueMap(state) {
state.selectValueMap = {
surveyType: '',
'curStatus.status': ''
}
},
changeSelectValueMap(state, { key, value }) {
state.selectValueMap[key] = value
},
resetButtonValueMap(state) {
state.buttonValueMap = {
'curStatus.date': '',
createDate: -1
}
},
changeButtonValueMap(state, { key, value }) {
state.buttonValueMap[key] = value
}
},
actions: {
async getSpaceList({ commit }) {
try {
const res = await getSpaceList()
if (res.code === CODE_MAP.SUCCESS) {
const { list } = res.data
const workSpace = list.map((item) => {
return {
id: item._id,
name: item.name
}
})
commit('setWorkSpaceList', list)
commit('updateSpaceMenus', workSpace)
} else {
ElMessage.error('getSpaceList' + res.errmsg)
}
} catch (err) {
ElMessage.error('getSpaceList' + err)
}
},
async addSpace({}, params) {
const res = await createSpace({
name: params.name,
description: params.description,
members: params.members
})
if (res.code === CODE_MAP.SUCCESS) {
ElMessage.success('添加成功')
} else {
ElMessage.error('createSpace code err' + res.errmsg)
}
},
async getSpaceDetail({ state, commit }, id) {
try {
const workspaceId = id || state.workSpaceId
const res = await getSpaceDetail(workspaceId)
if (res.code === CODE_MAP.SUCCESS) {
commit('setSpaceDetail', res.data)
} else {
ElMessage.error('getSpaceList' + res.errmsg)
}
} catch (err) {
ElMessage.error('getSpaceList' + err)
}
},
async updateSpace({}, params) {
const res = await updateSpace({
workspaceId: params._id,
name: params.name,
description: params.description,
members: params.members
})
if (res.code === CODE_MAP.SUCCESS) {
ElMessage.success('更新成功')
} else {
ElMessage.error(res.errmsg)
}
},
async deleteSpace({}, workspaceId) {
try {
const res = await deleteSpace(workspaceId)
if (res.code === CODE_MAP.SUCCESS) {
ElMessage.success('删除成功')
} else {
ElMessage.error(res.errmsg)
}
} catch (err) {
ElMessage.error(err)
}
},
async getSurveyList({ state, getters, commit }, payload) {
const filterString = JSON.stringify(
getters.listFilter.filter((item) => {
return item.condition[0].value
})
)
const orderString = JSON.stringify(getters.listOrder)
try {
let params = {
curPage: payload?.curPage || 1,
pageSize: payload?.pageSize || 10, // 默认一页10条
filter: filterString,
order: orderString,
workspaceId: state.workSpaceId
}
// if(payload?.order) {
// params.order = payload.order
// }
// if(payload.filter) {
// params.filter = payload.filter
// }
// if(payload?.workspaceId) {
// params.workspaceId = payload.workspaceId
// }
const res = await surveyList(params)
if (res.code === CODE_MAP.SUCCESS) {
commit('setSurveyList', res.data.data)
commit('setSurveyTotal', res.data.count)
} else {
ElMessage.error(res.errmsg)
}
} catch (error) {
ElMessage.error('getSurveyList status' + error)
}
}
}
}

View File

@ -1,8 +0,0 @@
export default {
setBannerList(state, data) {
state.bannerList = data
},
setCooperPermissions(state, data) {
state.cooperPermissions = data
}
}

View File

@ -1,5 +0,0 @@
import { SurveyPermissions } from '@/management/utils/types/workSpace'
export default {
bannerList: [],
cooperPermissions: Object.values(SurveyPermissions)
}

View File

@ -1,64 +0,0 @@
const USER_INFO_KEY = 'surveyUserInfo'
export default {
namespaced: true,
state: {
userInfo: {
token: '',
username: ''
},
hasLogined: false,
loginTime: null,
initialized: false
},
mutations: {
setUserInfo(state, data) {
state.userInfo = data
},
setHsLogined(state, data) {
state.hasLogined = data
},
setLoginTime(state, data) {
state.loginTime = data
},
setInitialized(state, data) {
state.initialized = data
}
},
actions: {
init({ dispatch, commit }) {
const localData = localStorage.getItem(USER_INFO_KEY)
if (localData) {
try {
const { userInfo, loginTime } = JSON.parse(localData)
if (Date.now() - loginTime > 7 * 3600000) {
localStorage.removeItem(USER_INFO_KEY)
} else {
dispatch('login', userInfo)
}
} catch (error) {
console.log(error)
}
}
commit('setInitialized', true)
},
login({ commit }, data) {
const loginTime = Date.now()
commit('setUserInfo', data)
commit('setHsLogined', true)
commit('setLoginTime', loginTime)
localStorage.setItem(
USER_INFO_KEY,
JSON.stringify({
userInfo: data,
loginTime: loginTime
})
)
},
logout({ commit }) {
commit('setUserInfo', null)
commit('setHsLogined', false)
localStorage.removeItem(USER_INFO_KEY)
}
}
}

View File

@ -7,6 +7,10 @@ import { getNewField } from '@/management/utils'
import submitFormConfig from '@/management/config/setterConfig/submitConfig'
import questionLoader from '@/materials/questions/questionLoader'
import { SurveyPermissions } from '@/management/utils/types/workSpace'
import { getBannerData } from '@/management/api/skin.js'
import { getCollaboratorPermissions } from '@/management/api/space'
import { CODE_MAP } from '../api/base'
const innerMetaConfig = {
submit: {
@ -262,8 +266,16 @@ function useCurrentEdit({
}
}
type IBannerItem = {
name: string
key: string
list: Array<Object>
}
type IBannerList = Record<string, IBannerItem>
export const useEditStore = defineStore('edit', () => {
const surveyId = ref('')
const bannerList: Ref<IBannerList> = ref({})
const cooperPermissions = ref(Object.values(SurveyPermissions))
const schemaUpdateTime = ref(Date.now())
const { schema, initSchema, getSchemaFromRemote } = useInitializeSchema(surveyId)
const questionDataList = toRef(schema, 'questionDataList')
@ -276,6 +288,18 @@ export const useEditStore = defineStore('edit', () => {
surveyId.value = id
}
const fetchBannerData = async () => {
const res: any = await getBannerData()
if (res.code === CODE_MAP.SUCCESS) {
bannerList.value = res.data
}
}
const fetchCooperPermissions = async (id: string) => {
const res: any = await getCollaboratorPermissions(id)
if (res.code === CODE_MAP.SUCCESS) {
cooperPermissions.value = res.data.permissions
}
}
const {
currentEditOne,
currentEditKey,
@ -319,6 +343,10 @@ export const useEditStore = defineStore('edit', () => {
return {
surveyId,
setSurveyId,
bannerList,
fetchBannerData,
cooperPermissions,
fetchCooperPermissions,
currentEditOne,
moduleConfig,
formConfigList,