3
1

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 3 years have passed since last update.

vuejsのwatchで複数の値を監視したい!!!

Posted at

初めに

Vuejsのwatchはとても便利で値の変化を監視することができます。

実現したかったこと

  • watchで2つの値を監視したい。

とのことで、僕は最初に

test-case1.vue
<template>
 <div>
  <input type="number" v-model="numberObj1">
  <input type="number" v-model="numberObj2">
  <p>{{ tashizan }}</p>
 </div>
</template>
<script>
 data() {
  return {
   numberObj1: '',
   numberObj2: '',
   tashizan: ''
  }
 },
 watch: {
  numberObj1 & numberObj2 () {
   this.tashizan = this.numberObj1 + this.numberObj2;
  }
 }
</script>

便利なVuejsだしこれで行けるやろ!ってどこかで思ってました。
そんなに世界は甘くはなかった。これでは行けなかった。

結論

sample.vue
<script>
(省略)
 computed: {
  MathObject() {
   return [this.numberObj1,this.numberObj2];
  }
 },
 watch: {
  MathObject (val) {
   this.tashizan = this.numberObj1 + this.numberObj2;
  }
 }
</script>

この方法で複数の値を監視することができました。
サンプルコードは短いからみやすいですけど、実業務になってくるとコードが長くなってくるのでこのMathObjectに何があるか分からないため、computedまで確認する必要性があるみたいです。
他の方とコードを共有している場合はコメントアウトなどを利用して変数を書いてあげると親切かもしれませんね。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?