티스토리 뷰

Vue.js

props 속성

부모 컴포넌트로부터 받아오는 props를 props 속성에 정의한다. 자식 컴포넌트에서는 부모 컴포넌트의 props를 변경해서는 안된다.

export default {
  props: {
    greetingMessage: String
  }
}
<span>{{ greetingMessage }}</span>
<MyComponent greeting-message="hello" />

 

filters 속성

사진에 씌우는 필터와 비슷하다고 생각하면 된다. 텍스트를 원하는 형식으로 바꾼다. 아래와 같은 형식으로 사용한다.

<!-- 중괄호 보간법 -->
{{ message | capitalize }}

<!-- v-bind 표현 -->
<div v-bind:id="rawId | formatId"></div>
filters: {
  capitalize: function (value) {
    if (!value) return ''
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}

 

<component> 태그

component 태그를 통해서 조건부 렌더링을 할 수 있다. :is=컴포넌트 이름으로 해당 컴포넌트를 렌더링 할 수 있다. :is에 변수를 넣어 그 값을 바꿔가며 렌더링을 하면 되겠다!

<component :is="about" />

 

<keepAlive> 태그

<component>를 감싸는 형태로 사용하며 이렇게 감싸주면 component가 전환될 때 state들을 초기화하지 않고 캐싱한다. include, exclude, max등의 속성을 설정해 줄 수 있다.

<keepAlive>
  <component :is="about" />
</keepAlive>

keepAlive 예제 링크

 


 

Vuex

mutations

상태 변이에 대한 핸들러를 정의한다. 직접 호출할 수 없으며 commit을 사용해야 한다. 동기적 처리를 할 때 사용하는 것을 추천한다.

mutations : { 
  increament(state) {
    state.count++
  } 
}

 

commit

상태 변이 핸들러(mutation)를 호출하기 위해 있다.

// store.commit(‘변이함수 이름’)
store.commit(‘increment’)

 

 payload를 가질 수도 있다.

// store.commit(‘변이함수 이름’, payload)
store.commit(‘increment’, 10)
mutations: {
  increment (state, n) {
    state.count += n
  }
}

 

객체를 사용해 호출하는 것도 가능하다. type이라는 속성에 변이 함수 이름을 넣으면 된다. 

// store.commit({type: ‘변이함수 이름’, payload name : value})
store.commit({type: ‘increment’, amount : 10})
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

 

actions

복잡한 처리나 비동기 처리를 해야 할 때 사용하는 걸 추천한다. 액션 핸들러는 저장소 인스턴스의 같은 메서드/프로퍼티 세트를 드러내는 컨텍스트 객체를 받는다. 보통 action으로 state를 변경하는걸 더 권장하는 것 같다.

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

action은 dispatch를 이용한다. dispatch에서 commit을 통해 mutation 함수를 실행한다. 

store.dispatch('increment')

 

payload나 객체로 dispatch도 가능하다.

// 페이로드와 함께 디스패치
store.dispatch('incrementAsync', {
  amount: 10
})

// 객체와 함께 디스패치
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

 

 

mutation vs action

mutation 은 동기처리 -> commit으로 호출

action 은 비동기처리 -> dispatch로 호출

action은 dispatch를 해서 commit을 할 수도 있다.

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

 

mapState나 mapActions와 같은 헬퍼를 사용해서 컴포넌트 내부에서 편하게 사용할 수 있다.

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함