簡體   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