View UI,即原先的 iView,从 2019 年 10 月起正式更名为 View UI,并使用全新的 Logo
问题描述:在使用 View UI (iview) 的 select 标签时,无意间发现一个问题,就是在select 标签中选中一个值,然后将 select 标签置空,获取 select 标签中的值为 undefined,此处正常应该为设置的空值,但实际却是undefined。有趣的是点击 2 次重置为空按钮后,却能获取到设置的空值
代码如下
<template>
<Form ref="formValidate1" :model="formValidate" :rules="ruleValidate" :label-width="80">
<FormItem label="City" prop="city">
<Select v-model="formValidate.city" filterable placeholder="Select your city">
<Option value="beijing">New York</Option>
<Option value="shanghai">London</Option>
<Option value="shenzhen">Sydney</Option>
</Select>
</FormItem>
<FormItem>
<Button type="primary" @click="handleSubmit('formValidate1')">Submit</Button>
<Button @click="handleReset('formValidate1')" style="margin-left: 8px">Reset</Button>
</FormItem>
</Form>
</template>
<script>
export default {
data () {
return {
formValidate: {
city: ''
},
ruleValidate: {
city: [
{ required: false, message: 'Please select the city', trigger: 'change' }
]
}
}
},
methods: {
handleSubmit (name) {
this.$refs[name].validate((valid) => {
if (valid) {
this.$Message.success('Success!');
console.log(JSON.stringify(this.formValidate))
console.log(this.formValidate.city)
} else {
this.$Message.error('Fail!');
}
})
},
handleReset (name) {
this.$refs[name].resetFields();
}
}
}
</script>
运行效果
将选中值置空后报 undefined
点击 2 次重置,反而有值了
解决办法:笔者在网上查找相关内容,发现很多人也遇到了同样的情况,最后在 View UI (iview) 的官方 github 上找到了解决办法,按照 View UI (iview) 官方的设计,select 标签绑定的值必须为 Option 中已存在的,知道了这一点,将代码改造如下,即在 Option 中添加一个默认空值,笔者这里添加了 <Option value="0">请选择城市</Option>,并将 city 默认值设为 '0'
<template>
<Form ref="formValidate1" :model="formValidate" :rules="ruleValidate" :label-width="80">
<FormItem label="City" prop="city">
<Select v-model="formValidate.city" filterable placeholder="Select your city">
<Option value="beijing">New York</Option>
<Option value="shanghai">London</Option>
<Option value="shenzhen">Sydney</Option>
<Option value="0">请选择城市</Option>
</Select>
</FormItem>
<FormItem>
<Button type="primary" @click="handleSubmit('formValidate1')">Submit</Button>
<Button @click="handleReset('formValidate1')" style="margin-left: 8px">Reset</Button>
</FormItem>
</Form>
</template>
<script>
export default {
data () {
return {
formValidate: {
city: '0'
},
ruleValidate: {
city: [
{ required: false, message: 'Please select the city', trigger: 'change' }
]
}
}
},
methods: {
handleSubmit (name) {
this.$refs[name].validate((valid) => {
if (valid) {
this.$Message.success('Success!');
console.log(JSON.stringify(this.formValidate))
console.log(this.formValidate.city)
} else {
this.$Message.error('Fail!');
}
})
},
handleReset (name) {
this.$refs[name].resetFields();
}
}
}
</script>
运行如下
参考文档:https://github.com/view-design/ViewUI/issues/446