0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

データの監視

Posted at

算出プロパティとウォッチャ — Vue.js

watchcomputedを使ってデータを監視するときにいろいろ大変だったのでメモ。
vueではdatacomputedにあるデータを監視して、変更を検知して何かしらfunctionを起こしたりとかが出来る。

今回やりたいこと

props[quote]の変更を検知して、quote_controllerにPOSTしたい。
ただし、quoteの中にはquote.choicesquote.roomがある。

元の状態

watch: {
    quote: {
      handler: function(newValue) {
        this.$http.post('//localhost:3000/quote', {
          choices: this.choices,
          room: this.room
        }).then((res) => {
          this.quote.sections = res.data
        })
      },
      deep: true
    }
}

何が問題なの?

handlerをつけると、配列の要素そのものが変更されたことを検知する。つまり、this.room = room1 => this.room = room2とか、this.choicesの要素の一つの内容だけ変わったとかも検知してくれる。deep: trueがないと、配列の要素の増減は検知してくれるけれど内容が変わったことは検知しない。

今回、roomに関しては内容の変更も検知してもらう必要がある。でないとroomに入っているのはいつも一つの要素だけだから永遠に検知されない。
でも、choicesに関してはpatternを変更すると一気に要素が入れ替わる為、その時に要素が変わったのをいちいち検知して永遠にPOSTされてしまった。
しかし、choicesroomは同時にPOSTする必要があるので別々にwatchしてPOSTアクションを起こすことは避けたい…

解決😇?

これで一旦正常に動いているように見える。


watch: {
    choices: function(newVal, oldVal) {
      this.change = true
      console.log("heyyyyyy")
    },
    room: {
      handler: function(newVal, oldVal) {
        this.change = true
        console.log("wowowowowowo")
      },
       deep: true
    },
    change: {
      handler: function(newVal, oldVal) {
        if(this.change) {
          this.$http.post('//localhost:3000/quote', {
            choices: this.choices,
            room: this.room
          }).then((res) => {
            this.quote.sections = res.data
          })
          console.log("www")
          this.change = false
        }
      }
    }
}

まず。datachangeを置く。
roomだけdeep: trueの状態にして、choicesroomの変更が検知されたらchange=trueとしてchange自体の変更もwatchする。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?