我在Vue JS中有一个组合框来选择多个项目,我想验证用户是否选择了任何项目或将其保留为空,但当我在控制台中打印组合框的长度和值时,如果用户选择了项目或不选择,问题总是会给出length==2,而值在这两种情况下都给出未定义的
HTML
<v-col cols="6">
<v-combobox class="xrfelements" :items="xrfElementsRatios" v-model="mainElementsRatios" :rules="notEmptyRule" label="Main Elements and Ratios" multiple required small-chips outlined dense></v-combobox>
</v-col>
java脚本
validateForm: function (e) {
if (document.getElementsByClassName("xrfelements").length) {
console.log(document.getElementsByClassName("xrfelements".values
return true;}
this.errors = [];
if (!document.getElementsByClassName("xrfelements").length){
console.log(document.getElementsByClassName("xrfelements").index)
console.log(document.getElementsByClassName("xrfelements".values)
this.errors.push('there is no element selected.')
}
if (this.errors.length)
{
this.$alert ("The following items should not be empty: " +this.errors.join(", "))
}
e.preventDefault(e);
},
像vue这样的框架不是这样工作的:您经常不直接与DOM交互。相反,您使用Vue中介。请学习Vue的基础知识。
new Vue({
el: '#app',
template: ` <v-col cols="6">
<v-combobox class="xrfelements" :items="xrfElementsRatios" v-model="mainElementsRatios" :rules="notEmptyRule" label="Main Elements and Ratios" multiple required small-chips outlined dense></v-combobox>
</v-col>`,
data() {
return {
notEmptyRule: [],
mainElementsRatios: [],
xrfElementsRatios: [],
}
},
methods: {
validateForm: function (e) {
if (mainElementsRatios.length) {
console.log(mainElementsRatios);
return true;
}
this.errors = [];
if (!mainElementsRatios.length) {
console.log(document.getElementsByClassName("xrfelements").index)
console.log(mainElementsRatios)
this.errors.push('there is no element selected.')
}
if (this.errors.length) {
this.$alert("The following items should not be empty: " + this.errors.join(", "))
}
e.preventDefault(e);
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>