vue.js - 在 vueJS 中跳过观察者
问题描述
我有一个用于更新文档实体的表格。
文档实体由员工列表(这是一个对象数组)组成,每个员工都有一个帖子,它只是一个字符串。
selectedEmployee
我有一个下拉列表(vue- multiselect的一种包装器),它接受员工数组并将选定的员工同步到data()
.
而且我还有一个观察者,当在下拉列表中选择员工时,selectedEmployee
它会自动设置输入。post
因此,当以表单创建文档时,一切都很好,但是,当我更新文档时,我从服务器获取现有文档,设置selectedEmployee
并设置员工的帖子。但是,该文档还保留了员工的帖子,所以当我第一次打开文档的表单以更新它时,我不想自动更新文档的帖子。我希望它仅在用户实际选择员工自己时才更新。
但是观察者也第一次被调用。
所以,想象一下我们有 John Doe 和他的经理。当我创建文档时,我将他的职位更改为设计师。然后,我打开文档表单以更新它,我应该看到对于这个特定文档,John Doe 的帖子是“设计师”,但是观察者被调用并将帖子返回给经理。
我试图在 data() 中创建一个假变量,doneFetching
比如假标志不是一种选择。
这是真实的代码示例(在我的情况下,员工 = 代表):
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)
}
},
解决方案
据我了解,您的问题是初始化组件时执行的观察程序。您是否尝试将观察者的即时属性设置为 false?
不是每个人都知道可以用不同的方式定义观察者。
大家都知道的简单的
watchers: {
propertyToWatch() { //code... }
}
将函数名称作为“字符串”传递
watchers: {
propertyToWatch: 'nameOfAfunctionDefinedInMethodsSection'
}
对象声明
这是声明观察者的最具描述性的方式。您将其编写为具有处理程序属性的对象(它可以是如上以字符串形式传递的函数的名称),以及其他属性,例如deep
监视对象的嵌套属性,或者在您的情况下immediate
告诉观察者是否应该安装组件后立即运行。
watchers: {
propertyToWatch: {
immediate: false,
handler: function() { //code.. }
}
}
推荐阅读
- reactjs - 反应:未捕获的类型错误:无法读取未定义的属性“确切”
- python - GroupBox 与 radioButtons 启用另一个 groupBox 不保持按钮状态
- php - 从 phpmailer 网络表单中的地址设置
- python - 获取 Python 中所有可能的变量/参数组合,但始终包括所有变量
- python - django 信号模块对象没有属性'post_save'
- sql - 当我使用内部联接时,我的一些行被删除了
- list - 检查两个键在字典列表中是否具有不同的值
- java - 打印最大元素及其索引位置
- .net - 对从 MongoDB 获取的数据库列表进行排序
- ios - 如何从“正在播放信息”中删除我的应用程序?