๐Ÿ“• Language/Vue

[Age of Vue] Vue.js ์‹œ์ž‘ํ•˜๊ธฐ - 5. Reactivity ๊ตฌํ˜„

a n u e 2022. 4. 27. 22:35

์•ž์„  HTML ๋ฌธ์ œ์ ์„ Vue ๊ธฐ๋Šฅ์ธ Reactivity๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•ด๋ณด์ž

 

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

    <script>
        var div = document.querySelector('#app');
        var viewModel = {}; //๊ฐ์ฒด ์„ ์–ธ

        // ๊ฐ์ฒด์˜ ๋™์ž‘์„ ์žฌ์ •์˜ํ•˜๋Š” API
        // Object.defineProperty(๋Œ€์ƒ ๊ฐ์ฒด, ๊ฐ์ฒด์˜ ์†์„ฑ, {
        //     ์ •์˜ ํ•  ๋‚ด์šฉ
        // });

        Object.defineProperty(viewModel, 'str', {
            //get: ์†์„ฑ์— ์ ‘๊ทผํ–ˆ์„ ๋•Œ์˜ ๋™์ž‘์„ ์ •์˜
            get: function() {
                console.log('์ ‘๊ทผ');
            },
            //set: ์†์„ฑ์— ๊ฐ’์„ ํ• ๋‹นํ–ˆ์„ ๋•Œ์˜ ๋™์ž‘์„ ์ •์˜
            set: function(newValue)
            {
                console.log('ํ• ๋‹น', newValue);
            }
        });
    </script>
</body>
</html>

 

 

 

์ด๋Ÿฌํ•œ ํŠน์„ฑ์„ Vue์˜ Reactivity ์ฆ‰, Vue์˜ ๋ฐ˜์‘์„ฑ์ด๋ผ๊ณ  ํ•œ๋‹ค.

str์ด ๋ณ€ํ–ˆ์„ ๋•Œ, ๊ณ„์†ํ•˜์—ฌ ๊ทธ ๋ณ€ํ•œ ๊ฐ’์— ๋งž์ถ”์–ด ๋ฐ์ดํ„ฐ๋ฅผ ๋ฟŒ๋ฆฌ๊ณ  ์‹ถ์œผ๋ฉด

defineProperty API์˜ set์—์„œ div์— newValue๋ฅผ innerHTML์„ ์ด์šฉํ•˜์—ฌ ์…‹ํŒ…ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

set: function(newValue)
{
    console.log('ํ• ๋‹น', newValue);
    div.innerHTML = newValue; 
}

 

๊ทธ๋Ÿผ newValue๊ฐ€ ๋ณ€ํ•  ๋•Œ ๋งˆ๋‹ค, ๊ฐ’์ด ์ž๋™์œผ๋กœ ์žฌํ• ๋‹น๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.