在vue中,表单验证传值是经常用到的。
首先vue的数据是双向绑定的,但是父组件向子组件传递数据是单向的,这就是单向数据流。
如果清楚了这一点,应该就能知道如何解决,编辑表单后 再次新增数据时 依然 是上次编辑的数据了。
解决思路:父组件点击编辑的时候向子组件传递要编辑的数据,点击新增的时候传递空的数据,子组件监听父组件传的值并赋值给表单数据
父组件:
<template>
<AddNewsType
:addType="addtype"
:visible.sync="visible"
:editData="editData"
@ok="handleOk"
></AddNewsType>
<template>
methods: {
// 新增
addAccounting() {
this.addtype = 1
this.visible = true
this.editData = {}
},
// 编辑
handleWorkEdit(edit) {
this.addtype = 2
this.visible = true
this.editData = edit
console.log('编辑的数据',this.editData)
},
}
子组件:
props: {
addType: {
type: Number,
default: 1,
},
visible: {
type: Boolean,
required: false,
},
editData: {
type: Object,
default: () => {},
},
},
watch:{
visible:{
handler(val) {
this.form = this.editData // 赋值给表单
if (!val) {
this.handleCancel()
}
},
}
},