【问题标题】:Vue2: Reacting on non existing input elementsVue2:对不存在的输入元素做出反应
【发布时间】:2017-06-12 16:22:33
【问题描述】:

我正在尝试创建一个验证,让表单字段根据不同的字段设置通过。在本例中,location2 输入不存在,因此 Vue 有效方法永远不会返回 true。 我的表单是服务器端动态的,所以我得到两组不同的字段。有时 location2 存在,应该在 Vue 中检查,有时它不存在,不应该检查。我不知道 Vue 内部是否有我可以做到这一点的东西。我已经尝试使用外部 Vue.set(App, 'location2', 'Test'); 取决于字段的存在,但这不是很好。

我希望这是可以理解的:)

<div id="app">   
  <input name="location" v-model="location" value="" type="text" required="required">
  <br />
  <!-- <input name="location2" v-model="location2" value="" type="text"required="required"> -->
  <p>
    Location: {{location}}
    <br /> Location2: {{location2}}
  </p>
  <button type="submit" :disabled="valid()">Go</button>
</div>

sd

new Vue({
  el: '#app',
  data: {
    location: '',
    location2: ''
  },
  methods: {
    valid: function() {

      return !(this.location != '' && this.location2 != '');
    }
  },
})

https://jsfiddle.net/bf1ge2xt/

【问题讨论】:

  • 你如何决定location2的输入是否被渲染?

标签: vue.js vuejs2


【解决方案1】:

如果你的输入的 name 属性总是要匹配你的 Vue 组件的数据属性,你的 valid 方法可以遍历组件中的每个 input 并检查具有相同名称的属性是否是有效:

valid: function() {
  let inputs = this.$el.querySelectorAll('input');
  for (let i = 0; i < inputs.length; i++) {
    if (this[inputs[i].name] == '') {
      return false;
    }
  }
  return true;
}

Here's a working fiddle.

【讨论】:

    【解决方案2】:

    你能检查一下 this.location2 是否设置了吗?

    new Vue({
      el: '#app',
      data: {
        location: '',
        location2: ''
      },
      methods: {
        valid: function() {
          if (this.location2) {
            return !(this.location != '' && this.location2 != '');
          }
          return this.location == '';
        }
      },
    })
    

    小提琴:https://jsfiddle.net/gratiafide/g92Lscu4/1/

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 2013-07-26
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多