计算的Setter作为验证器

时间:2018-03-21 16:01:14

标签: validation vue.js computed-properties element-ui

我尝试使用计算属性来监控ElementUI el-input组件中的值,但我想要的值没有显示在组件中。具体来说,当用户输入一个输入时,我想将长度限制为三个字符而不输入更多。例如,我不想要用户输入5个字符的行为,然后当el-input不在焦点时,该值会得到纠正。我意识到有maxlength属性,但我想让验证更通用。作为对此的扩展,我希望能够在el-input的内容上调用任何类型的函数并显示该函数的结果。这就是我现在正在做的事情:

模板:

    <el-input
        :placeholder="placeholder"
        :value="inputValue"
        @keypress.enter.native="$emit('keypress-enter',event)"
        @input="input"
        :disabled="disabled"
        :autosize="true"
        :readonly="readonly"
        :type="inputType"
        :rows="rows"
        v-model="inputValue"
        > 
    </el-input>

脚本:

computed: {
    inputValue: {
        get: function(){
            return this.temp;
            // This is what I eventually want to do
            // return this.validationFunction.f(this.temp);
        },
        set: function(newVal) {
            // This is what I'm doing right now to test
            this.temp = "";
            this.temp = (newVal.length > 3) ? newVal.slice(0,3) : newVal;
        }
    },
},
data: {
    return {
        temp: ""
    }
}

获得理想行为的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

setter正在运行但el-input不知道。问题是,当inputValue的值停止变化时,Vue认为它不需要通知任何人。

因此您必须更改该值,然后在$nextTick中将其更改为您希望的值。这样通知总会发生。遗憾的是,我不知道只是告诉Vue发送有关计算或数据项的通知。

new Vue({
  el: '#app',
  data: {
    temp: 'a'
  },
  computed: {
    inputValue: {
      get() {
        return this.temp;
      },
      set(newValue) {
        this.temp = newValue;
        this.$nextTick(() => {
          this.temp = newValue.substr(0, 3);
        });
      }
    }
  }
});
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui/lib/index.js"></script>

<div id="app">
  <el-input v-model="inputValue"></el-input>
  Actual value: {{ temp }}
</div>

相关问题