Vue.js中如何判断Multi-select组件是否为空?
如何正确判断VueForm Multiselect组件是否为空?
我尝试判断Multi-select组件是否为空,但检查时它始终显示不为空。请问是否需要使用v-model来实现该判断?
1. Multi-select组件代码
<template> <div> <Multiselect v-model="value" mode="tags" :close-on-select="false" :searchable="false" :create-option="true" :options="multi_options" class="multiselect-orange multiselect" /> </div> </template> <script> import Multiselect from "@vueform/multiselect"; export default { components: { Multiselect, }, props: { multi_options: { type: Array, required: true, }, inputSelected:{ required:true, }, method: { type: Function }, }, data() { return { value: this.inputSelected, }; }, mounted() { this.$emit("set-input", this.value); }, watch: { value: function () { this.$emit("set-input", this.value); }, }, }; </script>
2. 组件使用代码
<div class="inputHolder"> <label class="body">Skills:</label> <MultiSelect :multi_options="this.skills" @set-input="setSkillSet" :inputSelected="staffSkills"/> </div>
3. 尝试判断为空的代码
checkForm(){ this.errors = [] if (this.staffSkills) { return true; } if(this.staffSkills === []){ this.errors.push('Select at least one.'); } if(this.errors.length){ return this.errors } }
问题原因及解决方法
你的判断逻辑有两个核心问题:
- 数组不能用
=== []判断为空:JS中两个数组是不同引用,[] === []永远返回false。 if (this.staffSkills)逻辑错误:空数组[]在布尔判断中是true,会直接跳过后续空值检查。
正确的判断方式
修改checkForm函数,通过数组长度判断是否为空:
checkForm() { this.errors = [] // 检查数组是否为空(长度为0) if (!this.staffSkills || this.staffSkills.length === 0) { this.errors.push('Select at least one.'); } // 有错误返回错误列表,否则返回true return this.errors.length > 0 ? this.errors : true; }
关于v-model的使用
你当前通过inputSelected传值+$emit同步的方式是可行的,不一定非要用v-model。如果想简化代码,可以修改子组件支持v-model:
修改子组件支持v-model
<template> <div> <Multiselect v-model="innerValue" mode="tags" :close-on-select="false" :searchable="false" :create-option="true" :options="multi_options" class="multiselect-orange multiselect" /> </div> </template> <script> import Multiselect from "@vueform/multiselect"; export default { components: { Multiselect, }, props: { multi_options: { type: Array, required: true, }, // 用value替代inputSelected,符合v-model规范 value: { required: true, }, method: { type: Function }, }, data() { return { innerValue: this.value, }; }, watch: { innerValue(newVal) { // 触发input事件,v-model自动同步父组件值 this.$emit('input', newVal); }, value(newVal) { // 父组件值更新时同步内部值 this.innerValue = newVal; } }, }; </script>
父组件使用v-model
<div class="inputHolder"> <label class="body">Skills:</label> <MultiSelect :multi_options="this.skills" v-model="staffSkills"/> </div>
这样父组件的staffSkills会自动和子组件同步,判断空值依然用staffSkills.length === 0即可。
内容的提问来源于stack exchange,提问作者Apple
相关产品推荐
相关产品推荐

