简体   繁体   English

vue.js v模型验证和显示字段

[英]vue.js v-model validation and display field

In this code: 在此代码中:

<button type="button @click="editing=true">Edit</button>
<form v-show="editing" @submit="onSubmit">
   <textarea v-model="text"></textarea>
</form>
<div> Current value: {{text}} </div>

new Vue({ //...
   data: {
     editing: false,
     text: 'initial value..'
   }
   methods: {
     onSubmit: function() { if (this.value.length < 5) alert("error") }
   }
}

How can I make sure that {{text}} displays only a validated value? 如何确保{{text}}仅显示经过验证的值? Do I have to create two data members - one for the form and another for display? 我是否必须创建两个数据成员-一个用于表单,另一个用于显示? that will lead to some mess in my code (I have many large forms). 这会导致我的代码混乱(我有很多大表格)。
Maybe there is a v-model update hook for validation? 也许有一个用于验证的v模型更新挂钩?
The point of this question - if it's possible to avoid having two data members. 这个问题的重点-是否有可能避免拥有两个数据成员。

v-model for a <textarea></textarea> translates to: <textarea></textarea> v-model转换为:

<textarea
    v-bind:value="text"
    v-on:input="text = $event.target.value">

So the answer to your last question is no, there's no hooks. 因此,您对最后一个问题的回答是“否”,没有钩子。 You either don't use v-model by implementing something like the code above or use a second variable to save the last valid string as you were considering in the question. 您要么不通过实现上面的代码来使用v-model ,要么使用第二个变量来保存问题中所考虑的最后一个有效字符串。 The latter could go as: 后者可以这样:

 const app = new Vue({ el: "#app", data: { editing: false, text: 'Initial value..', lastValid: 'Initial value..', }, watch: { text(value) { if (value.length > 4) { this.lastValid = value; } }, }, }) 
 <script src="https://unpkg.com/vue"></script> <div id="app"> <div> <form> <textarea v-model="text "></textarea> </form> <div> Current value (legth > 4): {{lastValid}} </div> </div> </div> 

You can save the last valid input (in this case length >= 5) and update it on every keydown event, then on the submit just send the last valid value stored 您可以保存最后一个有效输入(在这种情况下,长度> = 5)并在每个按键事件中更新它,然后在提交时只发送存储的最后一个有效值

 new Vue({ el: '#app', data() { return { text: 'initial value..', lastValid: 'initial value..' } }, methods: { submit() { alert(this.lastValid) }, textChange($event) { let newText = $event.target.value this.lastValid = newText.length < 5 ? this.lastValid : newText } } }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script> <div id="app"> <form> <textarea v-model="text" @keydown="textChange"></textarea> <input type="submit" value="Send" @click="submit" /> </form> {{ lastValid }} </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM