[๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ปTA9 ์ธํ„ด 69์ผ์ฐจ]Vue.js-computed, mapState, mapMutations, mapActions

Goofiยท2023๋…„ 9์›” 25์ผ
0

computed

  • ์ผ์ข…์˜ ํ•จ์ˆ˜๋ณด๋‹ค๋Š” ๋ฐ์ดํ„ฐ ๊ณ„์‚ฐ๊ฒฐ๊ณผ ์ €์žฅ๊ณต๊ฐ„์œผ๋กœ ๋ด๋„ ๋œ๋‹ค.
  • state ํ•˜๋‚˜ ๊บผ๋‚ด์“ธ ๋•Œ๋„ computed ์•ˆ์— ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•์ด๋‹ค.
  • computed ํ•จ์ˆ˜๋Š” ๊ผญ return์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.
  • computed ํ•จ์ˆ˜๋ฅผ ๊ฐ€์ ธ๋‹ค๊ฐ€ ์“ธ ๋•Œ๋Š” ์†Œ๊ด„ํ˜ธ์—†์ด ํ•จ์ˆ˜๋ช…๋งŒ ์“ฐ๋ฉด ๋œ๋‹ค.
<p>ํ˜„์žฌ ๋‚ ์งœ : {{now}}</p>
computed : {
	now(){
		return new Datae()
    }
}

methods ์™€ computed ๋น„๊ต

  • methods ์•ˆ์— ๋งŒ๋“  ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋ถ€๋ฅผ ๋•Œ๋งˆ๋‹ค ์•ˆ์˜ ์ฝ”๋“œ๊ฐ€ ์‹คํ–‰๋œ๋‹ค.
  • computed ์•ˆ์— ๋งŒ๋“  ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋ถˆ๋Ÿฌ๋„ ์•ˆ์˜ ์ฝ”๋“œ๊ฐ€ ์‹คํ–‰์ด ์•ˆ๋œ๋‹ค.
    ์ฆ‰, ์ปดํฌ๋„ŒํŠธ๋กœ๋“œ์‹œ ํ•œ๋ฒˆ ์‹คํ–‰๋˜๊ณ  ๊ทธ ๊ฐ’์„ ๊ณ„์† ์ €์žฅํ•ด์„œ ์“ด๋‹ค.
    ์ผ์ข…์˜ ๊ณ„์‚ฐ๊ฒฐ๊ณผ ์ €์žฅ๊ณต๊ฐ„์ด๋ผ๊ณ  ๋ณด๋ฉด ๋œ๋‹ค.

computed ์“ฐ๋ฉด state ๊บผ๋‚ด๋Š” ์ฝ”๋“œ๊ฐ€ ์งง์•„์ง„๋‹ค.

computed : {
	name(){
    	return this.$store.state.name
    }
}

์Šคํฌ๋ฆฝํŠธ ํƒœ๊ทธ ์•ˆ์—์„œ store์“ฐ๋ ค๋ฉดthis.store์“ฐ๋ ค๋ฉด this.store์ด๋‹ค.

โ—๏ธ๋‹จ์ ) ๊บผ๋‚ผ state๊ฐ€ 100๊ฐ€ ์žˆ์œผ๋ฉด computed๋„ ๋ณต์žกํ•ด์ง„๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— mapState๋ฅผ ์ด์šฉํ•˜๋ฉด ๋œ๋‹ค.

mapState

  • mapState๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด computed ์ฝ”๋“œ๊ฐ€ ์งง์•„์ง„๋‹ค.
  • vuex state ํ•œ๋ฒˆ์— ๊บผ๋‚ด์“ฐ๋ ค๋ฉด ...mapState๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.
import {mapState} from 'vuex'

computed : {
	...mapState(['state์ด๋ฆ„1','state์ด๋ฆ„2'])
}

์ž‘๋ช…๊ฐ€๋Šฅ

import {mapState} from 'vuex'

computed : {
	...mapState({ ์ž‘๋ช… : 'state์ด๋ฆ„1' })
}

mapMutations

import {mapState, mapMutations} from 'vuex'

computed : {
	...mapState(['state์ด๋ฆ„1', 'state์ด๋ฆ„2']),
    ...mapMutaions(['์ข‹์•„์š”', 'setMore'])
}

$store.commit('์ข‹์•„์š”')๊ฐ€ ์•„๋‹ˆ๋ผ ์œ„์— mapMutations์— ์ •์˜ํ•ด ๋†“์œผ๋ฉด ์ข‹์•„์š”()๋กœ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•˜๋‹ค.

mapActions

//App.vue
import { mapActions } from 'vuex'

computed : {
	...mapActions(['delayClickBtn'])
}
//store.js
actions:{
	delayClickBtn(context){
    	setTimeout(() => context.commit('clickBtn'),2000);
    }
}
profile
์˜ค๋Š˜๋ณด๋‹จ ๋‚ด์ผ์ด ๊ฐ•ํ•œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค!!๐Ÿง‘๐Ÿปโ€๐Ÿ’ป

0๊ฐœ์˜ ๋Œ“๊ธ€