정리/Vue.js

Vue.js 템플릿 문법 - watch

알렉스 페레이라 2023. 9. 22. 15:55

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

 

사용법

<!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">
        {{num}}
        <button v-on:click="addNum">increase</button>
    </div>

    <script src="https://unpkg.com/vue@3"></script>
    <script>
        var vm = Vue.createApp({
            data(){
                return{
                    num : 10
                }
            },
            watch:{
                num: function(){
                    this.logText();
                }
            },
            methods:{
                addNum(){
                    this.num +=1;
                },
                logText(){
                    console.log('changed');
                }
            }
        });
        vm.mount('#app');
    </script>
</body>
</html>

 

watch와 computed의 차이점?

computed는 간단한 연산 위주, watch는 특정 메소드나 무거운연산, 혹은 비동기통신과같은 기능에 사용하는것이 좋다.

참고:https://vuejs.org/guide/essentials/computed.html#ad

 

Computed Properties | Vue.js

VueConf Toronto - Join the premier Vue.js conference | 9-10 Nov 2023 - Toronto, CanadaRegister Now Use code VUEJS to get 15% off

vuejs.org

 

 

예제

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    {{ num }}
  </div>

  <script src="https://unpkg.com/vue@3"></script>
  <script>
    var vm = Vue.createApp({
      data(){
        return{
            num : 10
        }
      },
      computed: {
        doubleNum() {
          return this.num * 2;
        }
      },
      watch: {
        num(newValue, oldValue) {
          this.fetchUserByNumber(newValue);
        }
      },
      methods: {
        fetchUserByNumber(num) {
          console.log(num);
        //   axios.get(num);
        }
      }
    }).mount('#app');
  </script>
</body>
</html>

computed속성을 이용한 클래스코드 작성방법

아래와같이 computed속성을 이용하여, 특정 data의 값을 이용해 클래스명을 지정할 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  .warning {
    color: red;
  }
  .blue-text{
    color: blue;
  }
  </style>
</head>
<body>
  <div id="app">
    <p v-bind:class="errorTextColor">Hello</p> <!-- isError가 참일때만 warning이 들어간다.-->
  </div>
  
  <script src="https://unpkg.com/vue@3"></script>
  <script>
    Vue.createApp({
      data(){
        return{
            //cname: 'blue-text',
            isError: true
        }
      },
      computed:{
        errorTextColor(){
            return this.isError ? 'warning' : null;
        }
      }
    }).mount('#app');
  </script>
</body>
</html>

'정리 > Vue.js' 카테고리의 다른 글

Vue.js 싱글 파일 컴포넌트 사용법  (1) 2023.09.26
Vue Cli란?  (0) 2023.09.25
Vue.js 템플릿 문법  (0) 2023.09.22
Vue.js에서 ajax사용하기 / axios란?  (0) 2023.09.21
Vue.js 2와 Vue.js3의 차이  (0) 2023.09.21