๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“  archive

[Vue.js] Vue ์—์„œ ๋น„๋™๊ธฐ ์š”์ฒญ์€ ์–ธ์ œ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„๊นŒ?

by HandHand 2022. 2. 20.

๋น„๋™๊ธฐ ์š”์ฒญ์œผ๋กœ ์ƒํƒœ๋ฅผ ์ดˆ๊ธฐํ™”ํ• ๋•Œ
์–ด๋–ค ๋ผ์ดํ”„์‚ฌ์ดํด์„ ์‚ฌ์šฉํ• ๊นŒ?

 

๐Ÿ“Œ ๋น„๋™๊ธฐ ์š”์ฒญ์„ ์œ„ํ•œ ์ตœ์ ์˜ ๋ผ์ดํ”„์‚ฌ์ดํด์€?

Vue ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด์„œ ํ•ญ์ƒ ๊ณ ๋ฏผํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค.

๋น„๋™๊ธฐ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ฌ ๋•Œ ์–ด๋–ค ๋ผ์ดํ”„์‚ฌ์ดํด ํ›…์—์„œ ์ด๋ฅผ ์ฒ˜๋ฆฌํ•ด์•ผ ํ• ๊นŒ?

๋งŽ์€ Vue ์‚ฌ์šฉ์ž๋“ค์ด created ์—์„œ ์ด๋ฅผ ์ฒ˜๋ฆฌํ•˜์—ฌ์„œ ์ € ๋˜ํ•œ ๋ง‰์—ฐํžˆ ์ด๋ฅผ ๋”ฐ๋ž๋Š”๋ฐ

Vue ์˜ ๋ผ์ดํ”„์‚ฌ์ดํด์„ ์ •๋ฆฌํ•˜๋ฉด์„œ ์ด์— ๋Œ€ํ•œ ๊ตฌ์ฒด์ ์ธ ๊ทผ๊ฑฐ๋ฅผ ์ฐพ๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค.

์ฐพ์•„๋ณด๋‹ˆ ์ด๊ฒŒ ์ •๋‹ต์ด๋‹ค! ํ•˜๋Š” ๊ฑด ์—†์—ˆ์ง€๋งŒ ๊ทธ์ค‘ ๊ฐ€์žฅ ๋‚ฉ๋“์ด ๋ ๋งŒํ•œ ๊ทผ๊ฑฐ๋ฅผ ๊ฐ€์ง€๋Š” ์ž๋ฃŒ๋ฅผ ์ฐพ์•˜์Šต๋‹ˆ๋‹ค.

 

๐Ÿ“Œ Vue ์‚ฌ์šฉ์ž๋“ค์˜ ๋ณดํŽธ์ ์ธ ์˜๊ฒฌ

ํ•ด์™ธ์˜ ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๋ถ„๋„ ์ €์™€ ๊ฐ™์€ ๊ณ ๋ฏผ์„ ํ•˜์…จ๊ณ 

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ทผ๊ฑฐ๋กœ created ํ›…์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

beforeCreate, created, beforeMount ์–ด๋””์—์„œ ํ˜ธ์ถœํ•˜๋”๋ผ๋„
๊ฒฐ๊ตญ์€ mounted ์ดํ›„์— ์‹ค์ œ ๋น„๋™๊ธฐ ์š”์ฒญ์ด ์ฒ˜๋ฆฌ๋œ๋‹ค.

     new Vue({
       el: '#app',
       beforeCreate() {
         setTimeout(() => { console.log('fastest asynchronous code ever') }, 0);
         console.log('beforeCreate hook done');
       },
       created() {
         console.log('created hook done');
       },
       beforeMount() {
         console.log('beforeMount hook done');
       },
       mounted() {
         console.log('mounted hook done');
       }
     })

     // ์œ„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ํ…Œ์ŠคํŠธํ•ด๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ฝ˜์†”์— ์ฐํž™๋‹ˆ๋‹ค.
     beforeCreate hook done
     created hook done
     beforeMount hook done
     mounted hook done
     fastest asynchronous code ever

์ด๋Š” ๊ฒฐ๊ตญ ์–ด๋Š ๋ผ์ดํ”„์‚ฌ์ดํด ํ›…์—์„œ ํ˜ธ์ถœํ•˜๋˜ ๊ฐ’์„ ๋ฐ›์•„์˜ค๊ฒŒ๋˜๋Š” ์‹œ์ ์ดmounted ํ›…์ด ํ˜ธ์ถœ๋œ ์ดํ›„๋ผ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

 

์ƒํƒœ๊ฐ’์€ beforeCreate ์™€ created ์‚ฌ์ด์—์„œ ์ดˆ๊ธฐํ™”๋œ๋‹ค.

์œ„์—์„œ ์‚ดํŽด๋ดค๋“ฏ์ด ์ปดํฌ๋„ŒํŠธ์˜ ์ƒํƒœ๊ฐ’์€ ์ด ๋‘ ๋ผ์ดํ”„์‚ฌ์ดํด ์‚ฌ์ด์—์„œ ์ดˆ๊ธฐํ™”๋˜๊ธฐ ๋•Œ๋ฌธ์—
๋น„๋™๊ธฐ๋กœ ๊ฐ’์„ ๊ฐ€์ ธ์™€ ์ƒํƒœ์— ์„ค์ •ํ•ด์•ผ ํ•œ๋‹ค๋ฉด created ํ›…์ด ๊ฐ€์žฅ ๋น ๋ฅธ ๋ผ์ดํ”„์‚ฌ์ดํด์ด ๋ฉ๋‹ˆ๋‹ค.

beforeCreate ๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋˜๋Š” ๊ฒฝ์šฐ๋Š”?

์ž‘์„ฑ์ž๋Š” ๋‹จ์ˆœํžˆ ๊ฐ€์žฅ ๋น ๋ฅด๊ฒŒ ํ˜ธ์ถœํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋  ๊ฒฝ์šฐ์—๋Š”
beforeCreate ๋ฅผ ์‚ฌ์šฉํ•˜๋„๋ก ๊ถŒ์žฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
๊ตณ์ด ์ƒํƒœ๊ฐ’์— ์ดˆ๊ธฐํ™”๊ฐ€ ํ•„์š”์—†๋‹ค๋ฉด beforeCreate ๊ฐ€ ๊ฐ€์žฅ ๋น ๋ฅธ ํ›…์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

Which VueJS lifecycle hook must Asynchronous HTTP requests be called in?

๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€