validation - How to apply min/max attribute to v-model in Vue? -
current constraint of min , max not respected due way v-on implemented:
<input id="passwordlength" class="form-control form-control-sm" type="number" min="5" max="35" v-model="options.length"> <span class="input-group-btn" v-on:click="options.length+=1"> <button class="btn btn-secondary" type="button"> <i class="fa fa-plus"></i> </button> </span> question
how can respect constrain , still keep elegant implementation?
you add custom modifier v-model directive:
// function gets min , max values element , prevents value of model going below min or above max function bindnumberinrange(el, binding, vnode) { let model = binding.expression; let min = parseint(el.min); let max = parseint(el.max); let val = parseint(binding.value); if ((min !== nan) && (min >= val)) { vnode.context[model] = min; } else if ((max !== nan) && (max <= val)) { vnode.context[model] = max; } el.value = val; } // original reference v-model directive let modeldirective = vue.directive('model') // set new definition of v-model directive vue.directive('model', { bind: function(el, binding, vnode) { // first fire original v-model bind hook modeldirective.bind(el, binding, vnode); if (binding.modifiers.range) { bindnumberinrange(el, binding, vnode) } }, componentupdated: function(el, binding, vnode) { // first fire original v-model componentupdated hook modeldirective.componentupdated(el, binding, vnode); if (binding.modifiers.range) { bindnumberinrange(el, binding, vnode) } } }) then, need add .range modifier v-model when want model respect min , max attributes of affected element:
<input type="number" min="4" max="10" v-model.range="foo"> here's codepen example.
here's vue's (semi-lacking) documentation on directives.
Comments
Post a Comment