【问题标题】:How to convert string to expression ( value ) in aurelia repeat for?如何在aurelia重复中将字符串转换为表达式(值)?
【发布时间】:2020-12-22 20:56:59
【问题描述】:

重复for循环中使用的数组

let loopArr = ["item.name + ' /'+ item.DisplayName? item.DisplayName: item.otherDisplayName", 
                    "item.description + ' /'+ item.anotherDescription"]

模板

<div repeat.for = item of data">
    <div repeat.for = "row of loopArr">
        <span textcontent.bind="renderRow(row, item)></span>
    </div>
</div>

组件方法

renderRow(row, item){
    return eval(row)
}

其实我想在模板中显示如下

<div repeat.for = item of data">
    <div repeat.for = "row of loopArr">
        <span>${item.name + ' /'+ item.DisplayName? item.DisplayName: item.otherDisplayName} </span>
        <span>${item.description + ' /'+ item.anotherDescription} </span>
    </div>
</div>

由于我想循环遍历dynamic loopArr,而不是使用eval从字符串转换为值,有没有更好的方法来计算字符串的值?此外,eval 不适用于多行语句,是否有任何其他方法/方式来处理上述问题?

如何将字符串转换为值并在aurelia模板中显示?

任何帮助将不胜感激!

【问题讨论】:

  • 你的问题不清楚(至少对我来说)。你能给我们一个你正在使用的示例数据集以及你想要在渲染后实现的 html 结果吗? gist.dumber.app 起点也不错,我们可以从该起点着手解决问题
  • 感谢您的回复,我现在得到了解决方案,下次我将添加一个工作示例

标签: javascript aurelia aurelia-templating


【解决方案1】:

我不确定您为什么要以字符串格式添加逻辑并使用eval。您可以直接将其添加到template 并显示:

<div repeat.for="item of data">
  <span>${item.name + '/' + (item.DisplayName ? item.DisplayName: item.otherDisplayName)}</span>
  <span>${item.description + ' / '+ item.anotherDescription} </span>
</div>

假设您有一个自定义字符串格式列表,并且您正在从另一个文件中导入它们。您可以创建一个函数数组,而不是字符串数组。与运行 eval

相比,这种延迟字符串创建的方法要好得多
displayTemplates = [
 item => item.name + '/' + (item.DisplayName ? item.DisplayName: item.otherDisplayName),
 item => item.description + '/'+ item.anotherDescription
] 

然后在template:

<div repeat.for="item of data">
  <template repeat.for="func of displayTemplates">
      <span>${ func(item) }</span> <!-- call each func on item object -->
    </template>
</div>

此外,您的字符串格式存在逻辑错误。与三元运算符相比,+ 运算符具有 higher precedence

所以,

item.name + '/' + item.DisplayName ? item.DisplayName : item.otherDisplayName

实际上被评估为

(item.name + '/' + item.DisplayName) ? item.DisplayName : item.otherDisplayName

因此,此表达式的计算结果将始终为 item.DisplayName,因为 item.name + '/' + item.DisplayName 永远不会是 falsy

需要在三元运算周围加上()

item.name + '/' + (item.DisplayName ? item.DisplayName: item.otherDisplayName)
// OR
item.name + '/' + (item.DisplayName ?? item.otherDisplayName)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2022-12-02
    • 2013-06-09
    • 2019-11-24
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多