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 1 year has passed since last update.

【Vue.js】watch(ウォッチャー)の使い方

Posted at

watch(ウォッチャー)とは

データの変更があった場合に、事前に登録した処理を実行する。

watchのvalueの中身

HTML
 <section id="events">
      <input type="text" v-model="name">
      <p>Your Name:{{ fullName }}</p>
    </section>
Javascript
const app = Vue.createApp({
  data() {
    return {
      fullName:''
    };
  },
  watch:{
    name(value){
      console.log(value)
    }
  },
}).mount('#events');

コンソールで引数valueの値を確認すると、
①入力値が変更される度に
②入力値がvalueに格納
されていることが分かる。

image.png

image.png

実践

watchの処理内容を以下のようにvalueを使ったものに変更する。

Javascript
  watch:{
    name(value){
      if(value === ''){
        this.fullName = ''
      }else{
        this.fullName = value + ' ' + 'yamada'
      }
    }
  }

image.png

おわりに

場合によってはcomputedの方が処理を短く書ける場合もある。
うまく活用していきたい。

参考

https://ja.vuejs.org/guide/essentials/watchers.html
Vueの勉強で活用中⇒https://www.udemy.com/course/vuejs-2-the-complete-guide/

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?