在Vue3+ElementPlus项目中,XML配置主要通过以下方式集成和运用:
- 配置获取与解析
javascript
// 从后端API获取XML配置
const { data } = await axios.get('/api/workflow/电梯维修工单')
// 浏览器端XML解析(也可在服务端转换JSON)
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(data, "text/xml");
const states = Array.from(xmlDoc.getElementsByTagName("State")).map(state => ({
id: state.getAttribute('id'),
actions: Array.from(state.getElementsByTagName("Action"))
}));
- 动态表单渲染
vue
<el-form :model="formData" v-if="currentState">
<template v-for="action in currentState.actions" :key="action.id">
<el-form-item
v-if="action.type === 'UPLOAD'"
:prop="action.field"
:label="action.getAttribute('label')">
<el-upload
:before-upload="validateFileType(action.getAttribute('accept'))">
<el-button type="primary">上传{{ action.field }}</el-button>
</el-upload>
</el-form-item>
<el-form-item
v-if="action.type === 'SELECT'"
:prop="action.field">
<el-select v-model="formData[action.field]">
<el-option
v-for="opt in parseOptions(action.textContent)"
:value="opt.value"
:label="opt.label"/>
</el-select>
</el-form-item>
</template>
</el-form>
- 条件渲染控制
javascript
// 解析XML中的条件表达式
import { compile } from 'expression-eval';
const visibleFields = computed(() => {
return currentState.value.actions.filter(action => {
const condition = action.querySelector('Visibility').getAttribute('condition');
return condition ? compile(condition)(formData.value) : true;
});
});
- 状态机集成
javascript
// 使用Pinia管理状态机
const workflowStore = useWorkflowStore();
watch(() => workflowStore.currentStateId, (newVal) => {
const stateNode = xmlDoc.querySelector(`State[id="${newVal}"]`);
currentState.value = {
id: newVal,
actions: parseActions(stateNode)
};
});
// 状态转换触发
const handleAction = (actionType) => {
const nextState = workflowStore.transition(actionType);
if (nextState) fetchNextStateConfig(nextState);
};
- 验证规则绑定
javascript
// 动态生成ElementPlus验证规则
const rules = ref({});
currentState.value.actions.forEach(action => {
const validations = action.querySelector('Validation');
if (validations) {
rules.value[action.field] = [
{
pattern: new RegExp(validations.getAttribute('regex')),
message: validations.getAttribute('message') || '格式错误'
}
];
}
});
技术整合特点:
- 响应式配置:XML配置变更后前端自动热更新(配合WebSocket)
- 组件动态注册 :根据
<Action type>
动态加载对应组件
javascript
const componentMap = {
UPLOAD: defineAsyncComponent(() => import('./ActionUpload.vue')),
SELECT: defineAsyncComponent(() => import('./ActionSelect.vue'))
};
- 配置缓存策略:使用localStorage缓存解析后的XML配置
- 开发环境联动 :通过vite-plugin-xml2json实现开发时代码提示
该方案在某物业系统中实现的效果:
- 工单详情页根据XML自动渲染不同表单布局
- 审批操作面板随状态动态变化(如图片上传/签字板/评分组件切换)
- 字段级权限控制(disabled/readonly状态由XML条件驱动)