Vue.js使用动态值

时间:2016-04-11 15:42:51

标签: html validation vue.js

我有一组错误,通过json传递给页面,如下所示;

"errors": [
    {
      "additional.1": [
        "[errored] field is required."
      ]
    },
    ....
]

在vue.js html中,我试图通过使用:class属性将类添加到已出错的字段中。基本上我需要查看错误[0] [additional.1]是否未定义。我唯一遇到的麻烦是[附加。[builder.key]]。似乎没有一种评估方法,所以它等于additional.1或任何builder.key应该是。

 <div :class="{'has-error' : typeof errors[$index] != 'undefined' && typeof errors[$index][additional.[builder.key]] != 'undefined' }" >

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我会将代码提取到一个方法中,使其更具可读性并清理模板:

<div :class="{'has-error': hasErrorAtIndex($index)}">

JS:

methods: {
  hasErrorAtIndex: function (index) {
    return typeof this.errors[index] != 'undefined' && this.errors[index].hasOwnProperty('additional.' + this.builder.key)
  }
}

...假设我猜错了builder.key的背景