【问题标题】:data-bind style with two arrays具有两个数组的数据绑定样式
【发布时间】:2022-07-05 03:23:41
【问题描述】:

我有两个数组,一个是警告,另一个是错误。

我想要实现的是使用 data.bind 读取错误和警告的长度,然后将输入字段边框更改为正确的颜色。

后面的打字稿代码处理警告和错误,我只需要看看我是否可以处理样式。

我目前有以下。

 <input type="text" data-bind="value: Value, valueUpdate: 'afterkeydown', attr: { class: WidgetType }, style: { border: Warning().length > 0 ? '3px solid #f5d531' : '2px solid #cccccc' ||  Error().length > 0 ? '3px solid #f00000' : '2px solid #cccccc' }" />

我想知道这在 HTML 中是否可行?

【问题讨论】:

    标签: html knockout.js


    【解决方案1】:

    这绝对是可能的,但你的表达有一个错误。你首先检查你的警告数组。如果有警告,则分配橙色。到目前为止,一切顺利。

    Warning().length > 0 
      ? '3px solid #f5d531'
      : /* else case */
    

    在没有警告的情况下,你有这个:

    '2px solid #cccccc' || /* Error check */
    

    由于"2px solid #cccccc" 是一个非空字符串,它永远不会评估|| 之后的错误检查。

    你可能想写:

    Warning().length > 0 ? '3px solid #f5d531' : Error().length > 0 ? '3px solid #f00000' : '2px solid #cccccc'
    

    在视图中塞入过多逻辑时,很容易引入此类错误。为了清理干净,我建议使用带有计算值的视图模型。例如:

    // Viewmodel code
    const hasError = ko.pureComputed(() => Error().length > 0);
    const hasWarning = ko.pureComputed(() => Warning().length > 0);
    
    const borderStyle = ko.pureComputed(() => {
      if (hasError()) return "3px solid #f00000";
      if (hasWarning()) return "3px solid #f5d531";
      return "2px solid #cccccc";
    });
    
    /* view */
    <input type="text" data-bind="
      value: Value,
      valueUpdate: 'afterkeydown',
      attr: { class: WidgetType },
      style: { border: borderStyle} " />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2019-01-09
      • 1970-01-01
      • 2020-06-25
      • 2018-12-08
      • 2012-09-01
      相关资源
      最近更新 更多