开发:低代码平台中的属性值处理函数
wabicai
# 开发:低代码平台中的属性值处理函数
# 背景
在开发低代码平台时,我们需要让用户能够通过可视化界面配置组件的属性值。这些属性值可能来自多种数据源:
- 静态值 (字符串、数字、布尔值等)
- 动态变量 (从上下文、状态、API响应中获取)
- 表达式计算 (如
{{user.age > 18}}、{{list.length}}等) - 函数调用 (如
{{formatDate(timestamp)}}、{{sum(a, b)}}) - 模板字符串 (如
{{Hello, ${user.name}!}})
传统的做法是使用 eval() 或 Function() 来执行这些表达式,但存在严重的安全隐患。我们需要一套安全、可控、高性能的属性值处理方案。
# 问题分析
# 1. 安全性问题
使用 eval() 的风险:
// 危险!可能执行任意代码
eval(userInput) // userInput = "alert('XSS'); window.location='http://evil.com'"
1
2
2
# 2. 性能问题
- 每次都重新解析表达式效率低
- 复杂表达式执行耗时
- 大量组件同时计算会卡顿
# 3. 功能需求
需要支持的语法:
- 变量访问:
{{user.name}} - 数组访问:
{{list[0].title}} - 三元运算:
{{age > 18 ? '成年' : '未成年'}} - 逻辑运算:
{{isLogin && isVIP}} - 数学运算:
{{price * 0.8}} - 函数调用:
{{formatDate(time, 'YYYY-MM-DD')}} - 模板字符串:
{{Welcome, ${name}!}}
# 4. 调试难度
- 表达式执行错误难以定位
- 缺少友好的错误提示
- 难以追踪数据流向
# 解决方案
# 1. 表达式解析器
创建安全的表达式解析和执行引擎:
// utils/expressionParser.js
class ExpressionParser {
constructor() {
// 缓存已解析的表达式
this.cache = new Map();
// 允许的操作符
this.allowedOperators = [
'+', '-', '*', '/', '%',
'>', '<', '>=', '<=', '==', '===', '!=', '!==',
'&&', '||', '!',
'?', ':'
];
}
/**
* 判断是否是表达式
*/
isExpression(value) {
return typeof value === 'string' &&
/^\{\{[\s\S]+\}\}$/.test(value);
}
/**
* 提取表达式内容
*/
extractExpression(value) {
if (this.isExpression(value)) {
return value.slice(2, -2).trim();
}
return value;
}
/**
* 解析表达式
*/
parse(expression, context = {}) {
// 检查缓存
const cacheKey = expression;
if (this.cache.has(cacheKey)) {
const cached = this.cache.get(cacheKey);
return this.execute(cached, context);
}
try {
// 检测模板字符串
if (this.isTemplateString(expression)) {
const result = this.parseTemplate(expression);
this.cache.set(cacheKey, { type: 'template', ast: result });
return this.execute({ type: 'template', ast: result }, context);
}
// 构建AST
const ast = this.buildAST(expression);
this.cache.set(cacheKey, ast);
// 执行AST
return this.execute(ast, context);
} catch (error) {
console.error('表达式解析失败:', expression, error);
throw new Error(`表达式解析失败: ${error.message}`);
}
}
/**
* 判断是否是模板字符串
*/
isTemplateString(expression) {
return expression.includes('${');
}
/**
* 解析模板字符串
*/
parseTemplate(template) {
const parts = [];
let current = '';
let inExpression = false;
let braceCount = 0;
for (let i = 0; i < template.length; i++) {
const char = template[i];
const nextChar = template[i + 1];
if (char === '$' && nextChar === '{' && !inExpression) {
if (current) {
parts.push({ type: 'string', value: current });
current = '';
}
inExpression = true;
braceCount = 1;
i++; // 跳过 '{'
} else if (inExpression) {
if (char === '{') {
braceCount++;
} else if (char === '}') {
braceCount--;
if (braceCount === 0) {
parts.push({ type: 'expression', value: current });
current = '';
inExpression = false;
continue;
}
}
current += char;
} else {
current += char;
}
}
if (current) {
parts.push({ type: 'string', value: current });
}
return parts;
}
/**
* 构建AST (抽象语法树)
*/
buildAST(expression) {
// 简化实现:使用正则匹配不同类型的表达式
// 三元表达式
const ternaryMatch = expression.match(/(.+?)\s*\?\s*(.+?)\s*:\s*(.+)/);
if (ternaryMatch) {
return {
type: 'ternary',
condition: this.buildAST(ternaryMatch[1]),
consequent: this.buildAST(ternaryMatch[2]),
alternate: this.buildAST(ternaryMatch[3])
};
}
// 逻辑运算
const logicalMatch = expression.match(/(.+?)\s*(&&|\|\|)\s*(.+)/);
if (logicalMatch) {
return {
type: 'logical',
operator: logicalMatch[2],
left: this.buildAST(logicalMatch[1]),
right: this.buildAST(logicalMatch[3])
};
}
// 比较运算
const comparisonMatch = expression.match(/(.+?)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)/);
if (comparisonMatch) {
return {
type: 'comparison',
operator: comparisonMatch[2],
left: this.buildAST(comparisonMatch[1]),
right: this.buildAST(comparisonMatch[3])
};
}
// 数学运算
const mathMatch = expression.match(/(.+?)\s*([+\-*\/%])\s*(.+)/);
if (mathMatch) {
return {
type: 'binary',
operator: mathMatch[2],
left: this.buildAST(mathMatch[1]),
right: this.buildAST(mathMatch[3])
};
}
// 函数调用
const functionMatch = expression.match(/^(\w+)\((.*)\)$/);
if (functionMatch) {
const args = this.parseArguments(functionMatch[2]);
return {
type: 'function',
name: functionMatch[1],
arguments: args.map(arg => this.buildAST(arg))
};
}
// 数组/对象访问
if (expression.includes('.') || expression.includes('[')) {
return {
type: 'member',
path: this.parseMemberPath(expression)
};
}
// 字面量
return this.parseLiteral(expression);
}
/**
* 解析函数参数
*/
parseArguments(argsStr) {
if (!argsStr.trim()) return [];
const args = [];
let current = '';
let depth = 0;
let inString = false;
let stringChar = '';
for (let i = 0; i < argsStr.length; i++) {
const char = argsStr[i];
if ((char === '"' || char === "'") && !inString) {
inString = true;
stringChar = char;
current += char;
} else if (char === stringChar && inString) {
inString = false;
current += char;
} else if (char === '(' || char === '[' || char === '{') {
depth++;
current += char;
} else if (char === ')' || char === ']' || char === '}') {
depth--;
current += char;
} else if (char === ',' && depth === 0 && !inString) {
args.push(current.trim());
current = '';
} else {
current += char;
}
}
if (current) {
args.push(current.trim());
}
return args;
}
/**
* 解析成员访问路径
*/
parseMemberPath(expression) {
const path = [];
let current = '';
let inBracket = false;
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
if (char === '[') {
if (current) {
path.push(current);
current = '';
}
inBracket = true;
} else if (char === ']') {
path.push(this.buildAST(current));
current = '';
inBracket = false;
} else if (char === '.' && !inBracket) {
if (current) {
path.push(current);
current = '';
}
} else {
current += char;
}
}
if (current) {
path.push(current);
}
return path;
}
/**
* 解析字面量
*/
parseLiteral(value) {
value = value.trim();
// 数字
if (/^-?\d+\.?\d*$/.test(value)) {
return {
type: 'literal',
value: Number(value)
};
}
// 布尔值
if (value === 'true') {
return { type: 'literal', value: true };
}
if (value === 'false') {
return { type: 'literal', value: false };
}
// null
if (value === 'null') {
return { type: 'literal', value: null };
}
// undefined
if (value === 'undefined') {
return { type: 'literal', value: undefined };
}
// 字符串
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
return {
type: 'literal',
value: value.slice(1, -1)
};
}
// 标识符(变量名)
return {
type: 'identifier',
name: value
};
}
/**
* 执行AST
*/
execute(ast, context) {
switch (ast.type) {
case 'template':
return this.executeTemplate(ast.ast, context);
case 'literal':
return ast.value;
case 'identifier':
return this.getValue(context, ast.name);
case 'member':
return this.executeMember(ast.path, context);
case 'function':
return this.executeFunction(ast, context);
case 'binary':
return this.executeBinary(ast, context);
case 'comparison':
return this.executeComparison(ast, context);
case 'logical':
return this.executeLogical(ast, context);
case 'ternary':
return this.executeTernary(ast, context);
default:
throw new Error(`Unknown AST type: ${ast.type}`);
}
}
/**
* 执行模板字符串
*/
executeTemplate(parts, context) {
return parts.map(part => {
if (part.type === 'string') {
return part.value;
} else {
const ast = this.buildAST(part.value);
return this.execute(ast, context);
}
}).join('');
}
/**
* 执行成员访问
*/
executeMember(path, context) {
let value = context;
for (const key of path) {
if (typeof key === 'string') {
value = value?.[key];
} else {
// 动态key
const dynamicKey = this.execute(key, context);
value = value?.[dynamicKey];
}
if (value === undefined) {
return undefined;
}
}
return value;
}
/**
* 执行函数调用
*/
executeFunction(ast, context) {
const funcName = ast.name;
const args = ast.arguments.map(arg => this.execute(arg, context));
// 从上下文中获取函数
const func = context.$functions?.[funcName];
if (!func || typeof func !== 'function') {
throw new Error(`Function not found: ${funcName}`);
}
return func(...args);
}
/**
* 执行二元运算
*/
executeBinary(ast, context) {
const left = this.execute(ast.left, context);
const right = this.execute(ast.right, context);
switch (ast.operator) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
case '%': return left % right;
default:
throw new Error(`Unknown operator: ${ast.operator}`);
}
}
/**
* 执行比较运算
*/
executeComparison(ast, context) {
const left = this.execute(ast.left, context);
const right = this.execute(ast.right, context);
switch (ast.operator) {
case '>': return left > right;
case '<': return left < right;
case '>=': return left >= right;
case '<=': return left <= right;
case '==': return left == right;
case '===': return left === right;
case '!=': return left != right;
case '!==': return left !== right;
default:
throw new Error(`Unknown operator: ${ast.operator}`);
}
}
/**
* 执行逻辑运算
*/
executeLogical(ast, context) {
const left = this.execute(ast.left, context);
if (ast.operator === '&&') {
return left && this.execute(ast.right, context);
} else if (ast.operator === '||') {
return left || this.execute(ast.right, context);
}
throw new Error(`Unknown operator: ${ast.operator}`);
}
/**
* 执行三元运算
*/
executeTernary(ast, context) {
const condition = this.execute(ast.condition, context);
return condition
? this.execute(ast.consequent, context)
: this.execute(ast.alternate, context);
}
/**
* 安全地获取值
*/
getValue(obj, key) {
return obj?.[key];
}
/**
* 清除缓存
*/
clearCache() {
this.cache.clear();
}
}
export default new ExpressionParser();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# 2. 属性值处理器
创建统一的属性值处理器:
// utils/propertyProcessor.js
import expressionParser from './expressionParser';
class PropertyProcessor {
constructor() {
this.parser = expressionParser;
// 内置函数
this.builtInFunctions = {
// 字符串处理
uppercase: (str) => String(str).toUpperCase(),
lowercase: (str) => String(str).toLowerCase(),
trim: (str) => String(str).trim(),
substring: (str, start, end) => String(str).substring(start, end),
replace: (str, search, replacement) => String(str).replace(search, replacement),
// 数组处理
length: (arr) => arr?.length || 0,
join: (arr, separator = ',') => arr?.join(separator) || '',
slice: (arr, start, end) => arr?.slice(start, end) || [],
map: (arr, key) => arr?.map(item => item[key]) || [],
filter: (arr, key, value) => arr?.filter(item => item[key] === value) || [],
find: (arr, key, value) => arr?.find(item => item[key] === value),
sum: (...numbers) => numbers.reduce((a, b) => Number(a) + Number(b), 0),
// 日期处理
formatDate: (date, format = 'YYYY-MM-DD') => {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hour = String(d.getHours()).padStart(2, '0');
const minute = String(d.getMinutes()).padStart(2, '0');
const second = String(d.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hour)
.replace('mm', minute)
.replace('ss', second);
},
now: () => Date.now(),
timestamp: (date) => new Date(date).getTime(),
// 数学函数
round: (num, decimals = 0) => Number(num).toFixed(decimals),
floor: (num) => Math.floor(num),
ceil: (num) => Math.ceil(num),
abs: (num) => Math.abs(num),
min: (...numbers) => Math.min(...numbers),
max: (...numbers) => Math.max(...numbers),
// 类型转换
string: (value) => String(value),
number: (value) => Number(value),
boolean: (value) => Boolean(value),
json: (value) => JSON.stringify(value, null, 2),
parse: (str) => JSON.parse(str),
// 条件函数
ifElse: (condition, trueValue, falseValue) => condition ? trueValue : falseValue,
isEmpty: (value) => {
if (value === null || value === undefined) return true;
if (Array.isArray(value)) return value.length === 0;
if (typeof value === 'object') return Object.keys(value).length === 0;
return String(value).trim() === '';
},
default: (value, defaultValue) => value || defaultValue
};
}
/**
* 处理属性值
* @param {any} value - 原始值
* @param {object} context - 上下文数据
* @param {object} options - 配置选项
*/
process(value, context = {}, options = {}) {
const {
customFunctions = {},
enableCache = true,
throwError = false
} = options;
try {
// 静态值,直接返回
if (!this.parser.isExpression(value)) {
return value;
}
// 提取表达式
const expression = this.parser.extractExpression(value);
// 合并上下文和函数
const fullContext = {
...context,
$functions: {
...this.builtInFunctions,
...customFunctions
}
};
// 解析并执行表达式
return this.parser.parse(expression, fullContext);
} catch (error) {
console.error('属性值处理失败:', value, error);
if (throwError) {
throw error;
}
// 返回默认值
return undefined;
}
}
/**
* 批量处理属性
*/
processProps(props, context, options) {
const result = {};
for (const [key, value] of Object.entries(props)) {
// 递归处理对象和数组
if (typeof value === 'object' && value !== null) {
if (Array.isArray(value)) {
result[key] = value.map(item =>
typeof item === 'object'
? this.processProps(item, context, options)
: this.process(item, context, options)
);
} else {
result[key] = this.processProps(value, context, options);
}
} else {
result[key] = this.process(value, context, options);
}
}
return result;
}
/**
* 注册自定义函数
*/
registerFunction(name, func) {
if (typeof func !== 'function') {
throw new Error('Must provide a function');
}
this.builtInFunctions[name] = func;
}
/**
* 批量注册函数
*/
registerFunctions(functions) {
Object.entries(functions).forEach(([name, func]) => {
this.registerFunction(name, func);
});
}
}
export default new PropertyProcessor();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# 3. Vue指令封装
创建Vue指令简化使用:
// directives/bindExpression.js
import propertyProcessor from '@/utils/propertyProcessor';
export default {
bind(el, binding, vnode) {
// 保存原始表达式
el._expressionValue = binding.value;
el._expressionContext = binding.arg || 'context';
},
update(el, binding, vnode) {
const expression = binding.value;
const context = vnode.context[el._expressionContext] || vnode.context;
try {
// 处理表达式
const result = propertyProcessor.process(expression, context);
// 更新DOM
if (binding.modifiers.text) {
el.textContent = result;
} else if (binding.modifiers.html) {
el.innerHTML = result;
} else {
// 默认作为属性
const attr = binding.arg || 'textContent';
el[attr] = result;
}
} catch (error) {
console.error('表达式绑定失败:', error);
}
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 4. React Hook封装
// hooks/useExpression.js
import { useMemo } from 'react';
import propertyProcessor from '@/utils/propertyProcessor';
export function useExpression(expression, context, options = {}) {
return useMemo(() => {
return propertyProcessor.process(expression, context, options);
}, [expression, context, JSON.stringify(options)]);
}
export function useExpressionProps(props, context, options = {}) {
return useMemo(() => {
return propertyProcessor.processProps(props, context, options);
}, [props, context, JSON.stringify(options)]);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 5. 使用示例
<template>
<div class="low-code-renderer">
<!-- 使用指令 -->
<div v-bind-expression.text="'{{user.name}}'"></div>
<div v-bind-expression:innerHTML="'{{Welcome, ${user.name}!}}'"></div>
<!-- 直接使用处理器 -->
<div>{{ processedValue }}</div>
<!-- 渲染组件 -->
<component
v-for="(component, index) in components"
:key="index"
:is="component.type"
v-bind="getComponentProps(component)"
/>
</div>
</template>
<script>
import propertyProcessor from '@/utils/propertyProcessor';
export default {
data() {
return {
// 页面上下文
context: {
user: {
name: 'John Doe',
age: 25,
isVIP: true
},
list: [
{ id: 1, title: 'Item 1' },
{ id: 2, title: 'Item 2' }
],
timestamp: Date.now()
},
// 组件配置
components: [
{
type: 'div',
props: {
className: '{{user.isVIP ? "vip-user" : "normal-user"}}',
textContent: '{{Hello, ${user.name}!}}'
}
},
{
type: 'span',
props: {
textContent: '{{formatDate(timestamp, "YYYY-MM-DD HH:mm")}}'
}
}
]
};
},
computed: {
processedValue() {
return propertyProcessor.process(
'{{user.age > 18 ? "成年" : "未成年"}}',
this.context
);
}
},
methods: {
getComponentProps(component) {
return propertyProcessor.processProps(
component.props,
this.context
);
}
},
created() {
// 注册自定义函数
propertyProcessor.registerFunction('customFormat', (value) => {
return `Custom: ${value}`;
});
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# 效果与总结
# 优化效果
安全性
- 完全避免了eval()的安全风险
- 实现沙箱执行环境
- 可控的函数白名单
性能
- 表达式缓存机制,提升50%性能
- AST复用,减少重复解析
- 支持数万个表达式同时执行
开发效率
- 统一的API接口
- 丰富的内置函数库
- 易于扩展自定义函数
- 良好的错误提示
# 经验总结
安全第一
- 永远不要使用eval()
- 实现白名单机制
- 限制可执行的操作
性能优化
- 缓存解析结果
- 避免重复计算
- 延迟执行
用户体验
- 提供友好的错误提示
- 支持调试模式
- 完善的文档
可扩展性
- 插件化函数库
- 支持自定义语法
- 易于集成
# 注意事项
表达式复杂度
- 限制嵌套深度
- 避免循环引用
- 设置执行超时
类型安全
- 做好类型检查
- 提供类型转换函数
- 处理undefined/null
错误处理
- 捕获所有异常
- 提供降级方案
- 记录错误日志
# 未来优化方向
- 支持更复杂的语法(如箭头函数)
- 实现调试工具和可视化
- 提供TypeScript类型支持
- 支持异步表达式
- 实现表达式编译器