gpt4 book ai didi

javascript - 输入文本框验证在 Vue js 中不起作用

转载 作者:行者123 更新时间:2023-11-30 19:11:32 24 4
gpt4 key购买 nike

当我点击添加一个带有空值的按钮时,列表中添加了空值。在这里我附上了截图。我需要验证一个空值。我的代码不工作。

错误输出:https://prnt.sc/pk0hvt

HTML:

<form
id="listadding-wrap"
@submit="checkForm"
action="#"
method="post"
>
<input type="text" class="form-control" v-model="newName">
<button class="addbtn" @click="addName">+</button>

<ul class="teamlist">
<li v-for="teamMember in teamMembers" v-text="teamMember"></li>
</ul>
<p v-if="errors.length">
<b>Please enter the value to add</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
</form>

VueJS:

var teammember = new Vue({

el: '#listadding-wrap',
data: {
errors: [],
newName:'',
teamMembers: ['']
},
methods: {
checkForm: function (e) {
if (this.newName) {
return true;
}
this.errors = [];

if (!this.newName) {
this.errors.push('Name required.');
}

e.preventDefault();
},

addName() {
this.teamMembers.push(this.newName);
this.newName = '';
}
},

});

最佳答案

您添加了 2 个事件处理程序,一个在表单 @submit 中,另一个在按钮 @click 中

上面代码中,按钮点击先触发,表单提交

我已将逻辑移至提交操作而不是两个单独的事件

这是工作代码

代码笔:https://codepen.io/chansv/pen/RwwRgqd

<form
id="listadding-wrap"
@submit="checkForm"
action="#"
method="post"
>
<input type="text" class="form-control" v-model="newName">
<button class="addbtn">+</button>

<ul class="teamlist">
<li v-for="teamMember in teamMembers" v-text="teamMember"></li>
</ul>
<p v-if="errors.length">
<b>Please enter the value to add</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
</form>

var teammember = new Vue({

el: '#listadding-wrap',
data: {
errors: [],
newName:'',
teamMembers: [],
},
methods: {
checkForm: function (e) {
console.log(e);
this.errors = [];

if (!this.newName) {
this.errors.push('Name required.');
} else {
this.teamMembers.push(this.newName);
this.newName = '';
}


e.preventDefault();
}
},

});

关于javascript - 输入文本框验证在 Vue js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com