没有eval的Vue3组合API模板替换



所以,我正在构建一个允许用户创建文档模板的系统。我有一个非常简单的、人类可读的方式来添加"动态"。数据到模板:

#firstName from client#"<——where "client"是ref(), firstName将是该对象的属性。

现在,我可以弄清楚如何用实际数据替换这些标签,而不使用eval()。现在,显然我不能相信人们在这里输入的内容,所以我有一个&;allowedtags &;数组,当我解析时,我只解析#..#值。所以他们不能做类似#someEvil code from SomeOtherEvilStuff"因为这是不允许的标签

这是真的那么糟糕,或者有另一种方法来动态替换使用ref()值?

function processTemplate(text: string): string {
const re = new RegExp(/#w+ from w+#/, 'g')
const matches = text.match(re) ?? []
for (const match of matches) {
if (!allowedTemplateTags.includes(match)) {
continue
}
const split = match.replace(/#/g, '').split(' from ')
const replaceRegEx = new RegExp(`(${match})`, 'g')
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
text = text.replace(replaceRegEx, eval(`${split[1]}?.value.${split[0]}`))
}
return text
}

基本上你想要的是访问变量你从用户那里得到名字?我的方法是使用一个响应式数据对象,并使用字符串指向正确的条目。

import { reactive } from ‘vue’;
// For the idea: these two strings you get from the user
const string1 = ‘firstName’;
const string2 = ‘client’;
const data = reactive({ 
client: {
firstName: ‘John’,
});
const text = data[string2][string1] // text will be ‘John’
data[string2][string1] = ‘Anna’; // now firstName will be ‘Anna’

我没有测试这段代码,但是我想你已经明白了。

希望对你有帮助。

最新更新