๐Ÿ“• Language/Vue

[Age of Vue] Vue.js ์‹œ์ž‘ํ•˜๊ธฐ - 26. watch ์†์„ฑ

a n u e 2022. 5. 8. 12:28

watch

data ๋ณ€ํ™”์— ๋”ฐ๋ผ, ํŠน์ • ๋กœ์ง์„ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ์†์„ฑ.

โ€ป computed์™€์˜ ์ฐจ์ด๊ฐ€ ๋ฌด์—‡์ผ๊นŒ?

computed๋Š” ๋‹จ์ˆœ ๊ฐ’์— ๋Œ€ํ•œ ๊ณ„์‚ฐ์ด๋‚˜ validation ์ฒ˜๋ฆฌ. watch๋Š” ๋งค๋ฒˆ ์‹คํ–‰๋˜๋Š” ๊ฒƒ์ด ๋ถ€๋‹ด์Šค๋Ÿฌ์šด ์กฐ๊ธˆ ๋” ๋ฌด๊ฑฐ์šด ๋กœ์ง์„ ๊ตฌํ˜„. ๋ฐ์ดํ„ฐ ์š”์ฒญ(axios)์— ์ ํ•ฉํ•˜์—ฌ methods ์†์„ฑ๊ณผ ๋ฌถ์–ด ์‚ฌ์šฉํ•จ.

 

"๊ณต์‹๋ฌธ์„œ์—๋Š” watch๋ณด๋‹ค computed ์“ฐ๊ธฐ๋ฅผ ๊ถŒ์žฅํ•จ"


<!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 }}
    {{ doubleNum }}
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        num: 10
      },
      //๊ธฐ์ค€์ด ๋˜๋Š” ๊ฐ’์€ data์˜ num
      //num์ด ๋ณ€๊ฒฝ๋ ๋•Œ๋งˆ๋‹ค ๊ณ„์‚ฐ๋˜์–ด์ง
      computed: {
        doubleNum: function() {
          return this.num * 2;
        }
      },
      watch: {
        num: function(newValue, oldValue) {
          this.fetchUserByNumber(newValue);
        }
      },
      methods: {
        fetchUserByNumber: function(num) {
          axios.get(num);
        }
      }
    });
  </script>
</body>
</html>