๐Ÿ“• Language/Vue

[vuejs] deep watch๊ฐ€ ๋ฐ˜ํ™˜ํ•œ ์ด์ „ ๊ฐ’์ด ํ˜„์žฌ ๊ฐ’๊ณผ ๋™์ผํ•œ ๊ฒฝ์šฐ

a n u e 2023. 1. 30. 16:03

 

state.thisYearTypeR์€ ๊ฐ์ฒด

ํ•ด๋‹น ๋ฐ์ดํ„ฐ์˜ ๋ณ€๊ฒฝ์„ ๊ฐ์ง€ํ•  ๋•Œ, ๋ณ€๊ฒฝ ์ „ ๋ฐ์ดํ„ฐ๊ฐ€ ํ•„์š”ํ•œ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

 

 

<์ž˜๋ชป๋œ ๋ฐฉ๋ฒ•>

const func = (value, preVal) => {
  console.log('ํ˜„์žฌ๊ฐ’', value);
  console.log('์ด์ „๊ฐ’', preVal);
};
    
watch(
  () => state.thisYearTypeR,
  async (val, preVal) => {
    await func(val, preVal);
  },
  {
    deep: true,
  }
);

์œ„์™€ ๊ฐ™์ด deep ํ”Œ๋ž˜๊ทธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ ๊ฐ์ง€ ์‹œ, ๋™์ผํ•œ ๋ฐฐ์—ด์„ ์ฐธ์กฐํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ƒˆ ๊ฐ’๊ณผ ๋™์ผํ•˜๋‹ค.

 

 

<๋ฌธ์ œ ํ•ด๊ฒฐ>

const func = (value, preVal) => {
  console.log('ํ˜„์žฌ๊ฐ’', value);
  console.log('์ด์ „๊ฐ’', preVal);
};
    
watch(
  () => ({ ...state.thisYearTypeR }),
  async (val, preVal) => {
    await func(val, preVal);
  },
  {
    deep: true,
  }
);
value {month1: 13, month2: 1, month3: 1, month4: 1, month5: 11, …}
preVal {month1: 3, month2: 1, month3: 1, month4: 1, month5: 11, …}