需求:点击新增弹框增加一条数据的时候,点击弹框确定的时候判断已添加的数据中是否有相同的数据,如有相同数据提示“已添加”
实现方式1
通过props 传参数,把已经添加过的数据(tableData)传到谈框里,弹框点击确定的时候,判断新添加的数据是否存在tableData 中
props:{
//表格已添加数据
tableData: {
type: Array,
default: () => ([]),
},
},
// 子组件保存
saveData(){
this.loading = true
this.confirmLoading = true
const data = Object.assign({}, this.form)
const creditCodes = this.tableData.map(item => item.creditCode)
if (creditCodes.includes(data.creditCode)) {
this.$message.warning('已添加!')
this.$refs['form'].resetFields()
this.visible = false
this.confirmLoading = false
this.loading = false
return
} else {
this.confirmLoading = false
this.loading = false
}
},
实现方式2:
通常子组件调用父组件方法:this.$emit(方法名, 传参1, 传参2),但是此方法的返回值是vue对象,而不是父组件方法的return值。此时要用到高阶函数,传函数作为参数,父组件里执行该函数。
//父组件新增--确定
handleAddOk(pData, callback){
let flag = true
const creditCodes = this.tableData.map(item => item.creditCode)
if (creditCodes.includes(pData.creditCode)) {
this.$message.warning('已添加!')
flag = false
callback(flag)
return
}
callback(flag)
this.tableData.unshift(pData)
this.$refs.table.setTableData(this.tableData)
// this.$nextTick(() => this.$refs.table.refresh())
},
// 子组件
saveData(){
this.loading = true
this.confirmLoading = true
const data = Object.assign({}, this.form)
this.$emit('add', data, flag =>{
if (flag) {
this.$refs['form'].resetFields()
this.visible = false
this.confirmLoading = false
this.loading = false
} else {
this.confirmLoading = false
this.loading = false
}
})
},