首页 > 解决方案 > 在 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)

  }
},

标签: vue.jsvuejs2

解决方案


据我了解,您的问题是初始化组件时执行的观察程序。您是否尝试将观察者的即时属性设置为 false?

不是每个人都知道可以用不同的方式定义观察者。

大家都知道的简单的

watchers: {
   propertyToWatch() { //code... }
}

将函数名称作为“字符串”传递

watchers: {
   propertyToWatch: 'nameOfAfunctionDefinedInMethodsSection'
}

对象声明

这是声明观察者的最具描述性的方式。您将其编写为具有处理程序属性的对象(它可以是如上以字符串形式传递的函数的名称),以及其他属性,例如deep监视对象的嵌套属性,或者在您的情况下immediate告诉观察者是否应该安装组件后立即运行。

watchers: {
   propertyToWatch: {
      immediate: false,
      handler: function() { //code.. }
   }
}

推荐阅读