繁体   English   中英

Vue3组合API模板替换没有eval

[英]Vue3 composition API template replacement without eval

因此,我正在构建一个允许用户创建文档模板的系统。 我有一种非常简单、人类可读的方式将“动态”数据添加到模板中:

#firstName from client#" <--- 其中“client”是 ref(),firstName 是该对象的属性。

现在,我可以弄清楚如何在不使用 eval() 的情况下用实际数据替换这些标签。 现在,显然我不能相信人们在这里输入的内容,所以我有一个“allowedTags”数组,当我解析时,我只解析 #..# 值的 RegEx 匹配列表。 因此,他们不能在此处从 SomeOtherEvilStuff 执行类似 #someEvil 代码之类的操作,因为它不是允许的标签。

这真的那么糟糕,还是有另一种方法可以使用 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’

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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM