VUE.JS

watch 속성 관련 정리

JUMP개발자 2020. 5. 5. 21:46

 

watch : watch 속성은 특정 데이터의 변화를 감지하여 자동으로 특정 로직을 수행해주는 속성임.

아래 소스의 경우 num 변수의 숫자가 변할 시에 watch가 그것을 감지하여 log를 찍는다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
 
  <div id="app">
    <p>{{ num }}</p>
    <button v-on:click="add">add</button>
  </div>
 
 
  <script>
      
    new Vue({
      el : '#app',
      data() {
        return {
        num : 10,    
        }
      },
 
      watch: {
        num : function() {
          this.logText();
        }
 
      },
 
      methods: {        
        add : function() {
          this.num = this.num +1;
        },
        logText : function() {
          console.log('changed'); 
        }
      },
    });
 
 
  </script>
 
</body>
</html>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter