This commit is contained in:
jxxghp
2025-03-22 10:03:11 +08:00
parent 6eabeb09c9
commit abfaf926c4
+22 -3
View File
@@ -49,9 +49,28 @@ const parseProps = (rawProps: Record<string, any>, model: Record<string, any>) =
model[value] = newValue model[value] = newValue
} }
} else if (key.startsWith('on')) { } else if (key.startsWith('on')) {
// 处理事件监听,值是函数的代码 // 处理事件监听,值是函数的代码 function xxx(e) { ... }
const eventName = key.replace('on', '').toLowerCase() if (typeof value === 'string') {
parsedProps[eventName] = new Function('model', `with(model) { return ${value} }`)(model) // 创建动态函数并绑定model上下文
const handler = new Function(
'model',
'event',
`
try {
with(model) {
return (${value})(event);
}
} catch(e) {
console.error('事件处理函数执行错误:', e);
}
`,
)
// 包装事件处理器,保持vue事件参数传递特性
parsedProps[key] = (...args: any[]) => {
const [event] = args
return handler(model, event)
}
}
} else { } else {
// 如果是表达式,需要绑定 // 如果是表达式,需要绑定
if (typeof value === 'string' && isExpression(value)) { if (typeof value === 'string' && isExpression(value)) {