store js를 어떻게 사용하는가?
main.js에서 vue store를 임폴트 해놨다. 그렇기에 프로젝트에서 vuex가 적용되었다고 생각할 수 있다.
https://www.youtube.com/watch?v=7i0D7OSogYc&list=PLZzSdj89sCN292abcbI3utND8pA1T1OyB&index=2
STORE.JS부분( getters 쓰는 방법 )
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { //data
allUsers:[
{userId: 'hoza123', password: '123', name: 'Hoza', address: 'Seoul', src:'https://goo.gl/oqLfJR'},
{userId: 'max123', password: '456', name: 'Max', address: 'Berlin', src:'https://goo.gl/Ksk9B9'},
{userId: 'lego123', password: '789', name: 'Lego', address: 'Busan', src:'https://goo.gl/x7SpCD'}
]
},
getters:{
allUsersCount: function(state){
return state.allUsers.length
},
countOfSeoul: state =>{
let count =0
state.allUsers.forEach(user =>{
if(user.address==='Seoul' || user.address==='seoul')count++
})
return count
},
percentOfSeoul: (state, getters)=>
{
return Math.round(getters.countOfSeoul/getters.allUsersCount *100 )
}
},
mutations: {
},
actions: {
}
})
// 이렇게 getters를 쓰면, vuex에 접근할 때 중복된 코드를 자꾸 쓴다. 이를 막기 위해서 getters를 쓴다.
=> computed의 장점인 반복된 코드를 줄여준다???? 이를 그대로 가지고 있다.
=> $store.state.allUsers.length 라고 쓰던거를 줄여서 쓸 수 있다.
=> $store.getters.allUsers 이런식으로 길이를 줄여서 쓸 수 있다.
=> 길이를 줄여줄 뿐만 아니라, 다른 원하는 함수를 만들어서 쓸 수도 있고, 중복된 코드를 줄여
쓸 수 있는 장점이 있다.
allUsers.vue에서 쓰는 방법
<template>
<div>
<h1>All Users{{count}}</h1>
<h1>All Users{{seoul}}</h1>
<h1>{{percent}}</h1>
<v-list two-line>
<v-list-tile
v-for="(user, index) in $store.state.allUsers"
:key="index"
avatar
>
<v-list-tile-avatar color="grey lighten-3">
<img :src="user.src">
</v-list-tile-avatar>
<v-list-tile-content>
<v-list-tile-title v-html="user.name"></v-list-tile-title>
<v-list-tile-sub-title>id:#{{index}} / {{user.address}} 거주</v-list-tile-sub-title>
</v-list-tile-content>
</v-list-tile>
</v-list>
</div>
</template>
<script>
import { EventBus } from '@/main.js'
import {mapState, mapGetters} from 'vuex'
export default {
data() {
return {
}
},
computed:{
...mapState['allUsers'],
...mapGetters({
count: 'allUsersCount',
seoul: 'countOfSeoul',
percent: 'PercentOfSeoul'
})
// ...mapGetters['allUsersCount', 'countOfSeoul','PercentOfSeoul']
},
mounted() {
EventBus.$on('signUp', users => {
this.$store.state.allUsers.push(users)
})
}
}
</script>
즉,
import {mapGetters} from 'vuex' 는 store에서 쓰지 않고 위와 같이 쓰는 곳에서
정의해준다.
getters에 있는 것들을 들고 와서 쓸 수 있도록 해준다.
...mapGetters({
count: 'allUsersCount',
seoul: 'countOfSeoul',
percent: 'PercentOfSeoul'
})
// ...mapGetters['allUsersCount', 'countOfSeoul','PercentOfSeoul']
이러한 명칭을 줄여서 쓸 수도 있다는 점은 참고 !!!
'개발 및 언어 > 뷰' 카테고리의 다른 글
vuex(state, getters, mutations, actions ) 역할 정리 (0) | 2020.02.24 |
---|---|
Mutation, Commit 쓰는 방법( 동기 역할을 한다고?) (0) | 2020.02.24 |
Mixin( 공통적으로 사용하는 부분) (0) | 2020.02.23 |
뷰 개발환경 ( 3.x- >4.x ) (0) | 2020.02.23 |
v-card (0) | 2020.02.19 |