Skip to content

Vuex store

Zin0_0 edited this page Nov 30, 2020 · 2 revisions

Vuex Store

  • State

    • ํ”„๋กœ์ ํŠธ์—์„œ ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜๋ฅผ ์ •์˜
    • ํ”„๋กœ์ ํŠธ ๋‚ด์˜ ๋ชจ๋“  ๊ณณ์—์„œ ์ฐธ์กฐ & ์‚ฌ์šฉ ๊ฐ€๋Šฅ
    • state๋ฅผ ํ†ตํ•ด ๊ฐ ์ปดํฌ๋„ŒํŠธ์—์„œ ๋™์ผํ•œ ๊ฐ’์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  • Mutations

    • state๋ฅผ ๋ณ€๊ฒฝ์‹œํ‚ค๋Š” ์—ญํ• 
    • ๋”ฐ๋ผ์„œ, Mutations๋ฅผ ์ด์šฉํ•ด์„œ๋งŒ state๋ฅผ ๋ณ€๊ฒฝํ•ด์•ผํ•œ๋‹ค.
    • ๋™๊ธฐ ์ฒ˜๋ฆฌ(๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ X)
    • ์œ„์˜ ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋˜๊ณ  ์ข…๋ฃŒ๋œ ํ›„ ๊ทธ ๋‹ค์Œ ์•„๋ž˜์˜ ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋œ๋‹ค.
    • commit('ํ•จ์ˆ˜๋ช…', '์ „๋‹ฌ ์ธ์ž')๋กœ ์‹คํ–‰
      • image
      • ์ด ๋•Œ, created ํ•จ์ˆ˜๋Š” arrow function์ด ์•„๋‹ˆ๋ผ created(): function() {} ์˜ ํ‘œํ˜„์„ ํ•ด์ค˜์•ผํ•œ๋‹ค. arrow function์˜ ๋‚ด๋ถ€ this๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์†Œ์œ ํ•œ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค์ง€ ์•Š๊ณ  ์ƒ์œ„ ์ปจํ…์ŠคํŠธ์ธ ์ „์—ญ ๊ฐ์ฒด windows๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. ๋”ฐ๋ผ์„œ, ES6์˜ ์ถ•์•ฝ ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ vue์˜ instance๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.
  • Actions

    • Mutations๋ฅผ ์‹คํ–‰ํ•˜๋Š” ์—ญํ• 
    • ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ(๋™๊ธฐ ์ฒ˜๋ฆฌ X)
    • ์ˆœ์„œ์— ์ƒ๊ด€ ์—†์ด, ๋จผ์ € ์ข…๋ฃŒ๋œ ํ•จ์ˆ˜์˜ ํ”ผ๋“œ๋ฐฑ์„ ๋ฐ›์•„ ํ›„์† ์ฒ˜๋ฆฌ๋ฅผ ํ•œ๋‹ค.
    • dispatch('ํ•จ์ˆ˜๋ช…', ์ „๋‹ฌ์ธ์ž)๋กœ ์‹คํ–‰
      • dispatch('Foo', somethingForState)
    • actions ๋‚ด์— ํ•จ์ˆ˜ ํ˜•ํƒœ๋กœ ์ž‘์„ฑ
    • ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ => ์ฝœ๋ฐฑํ•จ์ˆ˜๋กœ ์ž‘์„ฑ
    • Actions ์‹คํ–‰ -> mutation ์‹คํ–‰ -> state ๋ณ€๊ฒฝ ์ด๋ผ ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.
  • Getters

    • ๊ฐ Components์˜ ๊ณ„์‚ฐ๋œ ์†์„ฑ์˜ ๊ณตํ†ต ์‚ฌ์šฉ ์ •์˜
    • ์—ฌ๋Ÿฌ Components์—์„œ ๋™์ผํ•œ ๊ณ„์‚ฐ๋œ ์†์„ฑ์ด ์‚ฌ์šฉ๋  ๊ฒฝ์šฐ Getters์—์„œ ์ •์˜ํ•ด์„œ ๊ณตํ†ต์œผ๋กœ ์‰ฝ๊ฒŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
    • ํ•˜์œ„ ๋ชจ๋“ˆ์˜ getters๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ ์œ„ํ•ด์„œ๋Š” this.$store.getters["๊ฒฝ๋กœ๋ช…/ํ•จ์ˆ˜๋ช…"];์„ ์‚ฌ์šฉ
  • ์ƒ์œ„ ๋ชจ๋“ˆ์˜ dispatch, commit ์‹คํ–‰ ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•

    • ํ•˜์œ„ ๋ชจ๋“ˆ์—์„œ ํ˜•์ œ or ๋ถ€๋ชจ ๋ชจ๋“ˆ์˜ state์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” rootState๋ฅผ ์‚ฌ์šฉ
    • Mutations๋‚˜ Actions ์‹คํ–‰ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š”, ์„ธ๋ฒˆ์งธ ์ธ์ž์— {root:true}๋ฅผ ์ง€์ •ํ•ด์ฃผ๋ฉด ๋จ
      • dispatch('Foo', 'something', {root:true})

Reference

Clone this wiki locally