【问题标题】:Skip watcher in vueJS在 vueJS 中跳过观察者
【发布时间】: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)

  }
},

【问题讨论】:

  • 你能把它分解一下吗?

标签: vue.js vuejs2


【解决方案1】:

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

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

大家都知道的简单的

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

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

watchers: {
   propertyToWatch: 'nameOfAfunctionDefinedInMethodsSection'
}

对象声明

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

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

【讨论】:

  • 我知道,但我认为默认情况下立即设置为 false。我会试着告诉你它是否有效,谢谢:)
  • 太好了,让我知道结果
  • 不,它不起作用.. :( 我将创建/挂载/观察器功能记录到控制台,结果发现即使立即设置为 false,观察器也会第一次触发...
猜你喜欢
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2021-10-20
  • 2018-01-03
相关资源
最近更新 更多