【发布时间】:2019-04-22 22:51:37
【问题描述】:
我有一个用于更新文档实体的表单。
文档实体由员工列表(对象数组)组成,每个员工都有一个帖子,它只是一个字符串。
我有一个下拉列表(vue-multiselect 的一种包装器),它接受员工数组并将所选员工同步到data() 中的selectedEmployee 变量。
我还有一个 selectedEmployee 的观察者,它会在下拉列表中选择员工时自动设置 post 输入。
因此,当以表单创建文档时,一切都很好,但是,当我更新文档时,我从服务器获取现有文档,设置 selectedEmployee 并设置员工的职位。但是,文档还保留了员工的帖子,所以当我第一次打开文档的表单以更新它时,我不想自动更新文档的帖子。我希望它仅在用户实际选择员工自己时才更新。
但是观察者也是第一次被调用。
所以,假设我们有 John Doe 和他的经理。当我创建文档时,我将他的职位更改为设计师。然后,我打开文档表单以更新它,我应该看到对于这个特定文档,John Doe 的帖子是“设计师”,但观察者被调用并将帖子返回给经理。
我试图在 data() 中创建一个假变量,例如 doneFetching,但它只有在我直接在 watcher 中更新这个 var 时才有效,这看起来很危险,另外,在其他实体中我有许多不同类型的选择员工,所以制作大量假旗帜不是一种选择。
这是真实的代码示例(在我的例子中,员工 = 代表):
selectedApproveRepresentative(representative) {
if (!representative) {
this.memoData.approve_representative_id = null
return
}
this.memoData.approve_representative_id = representative.id
// Here is temporary solution, but I have many watchers for many different kinds of employees. If I move the doneFetching flag after I initialized the form, it'll be set to true, and only after that the watcher will be called
if (this.mode === 'update' && !this.doneFetching) {
this.doneFetching = true
return
}
// In normal case a representative might have or have not post, so depending on this case we set it to be empty or filled. But this should not be called the first time I open the form
this.memoData.approve_representative_post_dative_case =
representative.post_dative_case ?
representative.post_dative_case : ''
},
这里是我初始化数据的地方:
created() {
if (this.memo) {
this.memoData = _.cloneDeep(this.memo)
this.selectedApproveRepresentative = _.cloneDeep(this.memo.approve_representative)
}
},
【问题讨论】:
-
你能把它分解一下吗?