본문 바로가기

Java Scripts/Vue.js

Vuex - State & Getter

728x90

Vuex: State Management Pattern + Library 

 

installation

npm install vuex --save

 

Core Concepts

  • Vuex application is the store. A "store" is basically a container that holds your application state.
  • Vuex 애플리케이션은 store 입니다. "저장소"는 기본적으로 애플리케이션 상태를 보관하는 컨테이너입니다.
  • Web application 에서 공통으로 참조하는 state 를 global 한 부분에 store 하여, application 내부의 다른 component 가 쉽게 access and update 할 수 있게 하였다.
  • This State is reactive. When one component updates the State, other components that are using that data get notified, automatically receiving the new value.
  • 이 State는 반응적입니다. 한 구성 요소가 State를 업데이트하면 해당 데이터를 사용하는 다른 components에 알림이 전송되고 자동으로 새 값이 수신됩니다.
  • 여러 component 에서 다양한 방법으로 변경을 하지 않도록 standard 를 만들어 사용한다

A State Management Pattern

While the Vue instance has a data property, the Vuex store has state. Both are reactive.

Vue 인스턴스에는 data 속성이 있지만 Vuex store 에는 state가 있습니다. 둘 다 반응적입니다.

While the instance has methods, which can update data, the store has Actions, which can update the state.

인스턴스에는 데이터를 업데이트할 수 있는 methods가 있는 반면, store 에는 상태를 업데이트할 수 있는 Actions이 있습니다.

While the instance has computed properties, the store has getters, which allow us to access filtered, derived, or computed state.

인스턴스에는 computed  속성이 있는 반면 store 에는 filtered, derived 또는 computed state에 액세스할 수 있는 getter가 있습니다.

Vuex provides a way to track state changes, with something called Mutations.

Vuex는 Mutations라는 기능을 통해 상태 변경을 추적하는 방법을 제공합니다.

We can use Actions to commit Mutations, and from the Vue DevTools, we can even trace back in time through a record of each mutation to the state.

Actions를 사용하여 Mutations를 커밋할 수 있으며 Vue DevTools에서 상태에 대한 각 변형 기록을 통해 시간을 거슬러 올라갈 수도 있습니다.

 

Getting Vuex State from Vue Components

the simplest way to "retrieve" state from it is simply returning some store state from within a computed property (opens new window):

상태를 "retrieve"하는 가장 간단한 방법은 단순히 computed 속성 내에서 일부 store state를 반환하는 것입니다.

Vuex provides a mechanism to "inject" the store into all child components from the root component with the store option (enabled by Vue.use(Vuex)):

Vuex는 store 옵션을 사용하여 루트 components 의 모든 하위 components  에 저장소를 "주입"하는 메커니즘을 제공합니다.

const app = new Vue({
  el: '#app',
  // provide the store using the "store" option.
  // this will inject the store instance to all child components.
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})

By providing the store option to the root instance, the store will be injected into all child components of the root and will be available on them as this.$store.

루트 인스턴스에 store  옵션을 제공하면 store 가 루트의 모든 하위 components 에 주입되고 this.$store로 사용할 수 있습니다.

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

 

State & Getters

Single State Tree

Vuex uses a single state tree - that is, this single object contains all your application level state and serves as the "single source of truth."

Vuex는 single state tree를 사용합니다. 즉, 이 단일 객체는 모든 애플리케이션 수준 state 를 포함하고 "단일 정보 소스" 역할을 합니다.

 

Accessing State

Add some State in store/index.js so we can look at how to access it from a component. We can create a user object.

store/index.js에 State를 추가하면 컴포넌트에서 State에 액세스하는 방법을 살펴볼 수 있습니다. user object를 만들 수 있습니다.

    state: {
      user: { id: 'abc123', name: 'Adam Jahr' }
    }

We can access this user State from anywhere in our app,

우리는 앱 어디에서나 이 사용자 상태에 접근할 수 있습니다.

    <template>
      <h1>Create Event, {{ $store.state.user }}</h1>
    </template>

We can use dot notation to pinpoint the exact property from our user State that we want to display.

점 표기법을 사용하여 표시하려는 사용자 상태의 정확한 속성을 찾아낼 수 있습니다.

    <template>
      <h1>Create Event, {{ $store.state.user.name }}</h1>
    </template>

But what if we needed to use the user’s name in multiple places within our component?

하지만 구성 요소 내의 여러 위치에서 사용자 이름을 사용해야 한다면 어떻게 될까요?

we could write it once, in a computed property, called userName.

userName이라는 computed  속성에 한 번만 작성할 수 있습니다.

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

This way, our template becomes more readable and less redundant.

이렇게 하면 템플릿이 더 읽기 쉽고 덜 중복됩니다.

    <h1>Create an Event, {{ userName }}</h1>
    <p>This event is created by {{ userName }}</p>

 

The mapState Helper

mapState helper generates computed properties for us.

mapState helper 는 computed  속성을 생성합니다.

 

For example, add some more State to our Vuex Store.

예를 들어 Vuex Store에 State를 더 추가해 보세요.

    state: {
      user: { id: 'abc123', name: 'Adam Jahr' },
      categories: ['sustainability', 'nature', 'animal welfare', 'housing', 'education', 'food', 'community']
    }

In EventCreate.vue, we can import mapState.

EventCreate.vue에서 mapState를 가져올 수 있습니다.

 import { mapState } from 'vuex'

Use it to map our State to a computed property that can retrieve our user’s name, and our categories.

이를 사용하여 사용자 이름과 카테고리를 검색할 수 있는 계산된 속성에 State를 매핑합니다.

    computed: mapState({
      userName: state => state.user.name,
      categories: state => state.categories
    })

There’s an even simpler way to access the top-level State (not using dot notation).

top-level 상태에 액세스하는 훨씬 더 간단한 방법이 있습니다(점 표기법을 사용하지 않음).

Using the State’s string value 'categories' is equivalent to "state => state.categories".

State의 문자열 값 'categories'를 사용하는 것은 "state => state.categories"와 동일합니다.

    computed: mapState({
      userName: state => state.user.name,
      categories: 'categories' // <-- simplified syntax for top-level State
    })

Simplify the mapState syntax even more by passing an array of strings of the State values we want to map to computed properties

계산된 속성에 매핑하려는 State 값의 문자열 배열을 전달하여 mapState 구문을 더욱 단순화합니다.

computed: mapState(['categories', 'user'])

Use dot notation to access our user’s name.

사용자 이름에 접근하려면 점 표기법을 사용하세요.

 <h1>Create an Event, {{ user.name }}</h1>

Object Spread Operator

mapState returns an object of computed properties. But it’s currently preventing us from adding additional, local computed properties that aren’t mapped to our Store’s State.

mapState는 계산된 속성의 객체를 반환합니다. 하지만 현재는 Store의 상태에 매핑되지 않은 추가 로컬 계산 속성을 추가할 수 없습니다.

Using the object spread operator, which allows us to mix in additional computed properties.

추가 computed 속성을 혼합할 수 있는 object spread operator,를 사용합니다.

    computed: {
      localComputed() {
        return something
      },
      ...mapState(['categories', 'user']) // <-- using object spread operator
    }

 

Getters

Sometimes we want to access derived state. In other words, we might want to process the state in some way when we access it.

때로는 파생된 상태에 액세스하고 싶을 때도 있습니다. 즉, 상태에 액세스할 때 어떤 방식으로든 상태를 처리하고 싶을 수도 있습니다.

For example, instead of accessing our State’s categories, we might want to know how many categories there are.

From within our component, we could use:

예를 들어, 우리 State의 카테고리에 액세스하는 대신 카테고리가 몇 개 있는지 알고 싶을 수도 있습니다.
component 내에서 다음을 사용할 수 있습니다.

  this.$store.state.categories.length

 

adding Getter to our Store in store.js

store.js의 스토어에 Getter 추가

getters: {
	catLength: state => {
		return state.categories.length
	}
}

 

 

Using our Getter in our EventCreate component in a computed property..

EventCreate component 요소의  계산된 속성 에서 Getter를 사용합니다.

    computed: {
      catLength() {
        return this.$store.getters.catLength
      }
    }

The length of our categories State changes, our catLength Getter will recalculate and our computed property will update accordingly.

카테고리 State 의 길이가 변경되면 catLength Getter가 다시 계산되고 computed된 속성이 그에 따라 업데이트됩니다.

 

 

Dynamic Getters

Can we retrieve some state based upon a parameter? Yes. we can achieve that by returning a function.

매개변수를 기반으로 일부 state를 검색할 수 있나요? 예. 우리는 함수를 반환함으로써 이를 달성할 수 있습니다.

note ) 아래 함수는 arrow 가 두번 연속해서 나오는 경우이고.  events 배열에서 각 event 를 넘겨쥬어 id 가 맞는 것이 발견되면 return 하는 구조임

    getEventById: (state) => (id) => {
      return state.events.find(event => event.id === id)
    }

 

in our component.

note) computed 에서는 param 이 정의되지 않았지만, 사용할때는 param 을 넘겨주고 있다

    computed: {
      getEvent() {
        return this.$store.getters.getEventById
      }
    }
    
    // in our template
     <p>{{ getEvent(1) }}</p>

The mapGetters Helper

map Getters to computed properties on our component

Getter를 component의 computed 속성에 매핑.

 import { mapGetters } from 'vuex'

 

We have an array of computed properties in our component that are mapped to our Getters.

Getter에 매핑된 component 에 computed 속성 배열이 있고, 이것을 component template 에서 쉽게 사용할 수 있다.

    computed: mapGetters([
      'categoriesLength',
      'getEventById'
    ])

 

If we want to rename these Getters, we can do so in an object:

이러한 Getter의 이름을 바꾸려면 객체에서 그렇게 할 수 있습니다.

    computed: mapGetters({
      catCount: 'categoriesLength',
      getEvent: 'getEventById'
    })

this.catCount is mapped to this.$store.getters.categoriesLength and getEvent is mapped to this.$store.getters.getEventById.

this.catCount는 this.$store.getters.categoriesLength에 매핑되고 getEvent는 this.$store.getters.getEventById에 매핑됩니다.

 

Object Spread Operator can mix these Getters in with local computed properties.

Object Spread Operator)는 이러한 Getter를 로컬 계산 속성과 혼합할 수 있습니다.

    computed: {
      localComputed() { return something }
      ...mapGetters({
        catCount: 'categoriesLength',
        getEvent: 'getEventById'
      })
    }

https://vuex.vuejs.org/guide/getters.html

 

Getters | Vuex

Getters Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them: computed: { doneTodosCount () { return this.$store.state.todos.filter(todo => todo.done).length } } If more than o

vuex.vuejs.org

https://github.com/tc39/proposal-object-rest-spread

 

GitHub - tc39/proposal-object-rest-spread: Rest/Spread Properties for ECMAScript

Rest/Spread Properties for ECMAScript. Contribute to tc39/proposal-object-rest-spread development by creating an account on GitHub.

github.com

https://github.com/Code-Pop/real-world-vue/releases/tag/lesson11-vuex-finish

 

Release lesson11-vuex-finish · Code-Pop/real-world-vue

lesson11-state&getters-finish

github.com

 

'Java Scripts > Vue.js' 카테고리의 다른 글

Vue Router Basics  (0) 2021.12.31
Vue : Slots: Fundamentals  (0) 2021.12.31
Vue 3 Forms : Submitting Forms  (0) 2021.12.29
Vue 3 : Lazy Validation  (0) 2021.12.28
Vue 3 : Tree shaking  (0) 2021.12.28