el-select allow-create判断是否为新添加项
- 应用场景 后台获取列表 前端可新添加项 新添加项与列表数据区分
- html
给标签 设置allow-create
和ref
属性
<el-select ref="company" v-model="form.company" filterable allow-create placeholder="请选择" @change="companyChange">
<el-option
v-for="item in companyList"
:key="item.id"
:label="item.name"
:value="item.id"/>
</el-select>
- 打印发现 一旦有先添加项目后 值会存在于
this.$refs.company.createdLabel
中,为避免先添加后切换导致添加值不为null
在每次change
后,先给createdLabel
值赋一次空值
ps
: 若没有来回切换的问题 可忽略这一步
companyChange() {
this.$refs.company.createdLabel = null
},
- 最终判断
if (this.$refs.company.createdLabel) {
// 新添加值
} else {
// 列表已有值
}
总结:判断是否新添加的值主要还是靠createdLabel
,至于使用时机 判断时机 都可灵活变通