Vue.js 객체 속성 및 문법, vuex 사용 형태 정리

SeoYng·2022년 1월 26일
0
post-thumbnail

Vue 객체 속성

<template>
    <div>
        <h1 @click.prevent="function1">template태그안은 html 코드 부분</h1>
        <p>{{msg}}</p>
        <!-- 자식 컴포넌트 사용 -->
        <child-component @onFunction1="function1" />
    </div>
</template>

<script>
// 모듈 및 컴포넌트 import
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';
import ChildComponent from './path';
// Vue 객체 export
export default {
    name: 'Parent', // *name: 이름

    components: { // *components: 사용할 컴포넌트 등록
	ChildComponent,
    },

    props:{ 
        // *props: 부모에서 내려주는 데이터 - 자식이 바꿀 수 없음
    },

    data() { // *data - 컴포넌트에서 사용하는 데이터 - 로컬 데이터 (지역 변수)
        // 충돌 방지 위해 return 형식으로 작성 해야 함
        return {
            msg: '<script>태그 안은 자바스크립트 영역 (이벤트 / 로직 처리)'
        };
    },

    // 라이프 사이클
    created() {
    // *created: vue인스턴스 생성 후 데이터에 관한 설정이 완료되고 나서 호출, 주로 데이터 init
        window.addEventListener('scroll', this.$_function2);
    },
    mounted() {
    // *mounted: vue인스턴스가 마운트 된후 호출
        this.$nextTick(() => {
           // $nextTick - 마운트 된후 dom이 그려지고 나서 호출
	});    
    },
    updated() {
    // *updated: 데이터가 변경되면 호출 됨 - 잘 사용하지 않음
    },
    beforeDestroy() {
    // *beforeDestroy: Vue 인스턴스가 제거되기전에 호출
        window.removeEventListener('scroll', this.$_handleScroll);
    },
    destroyed() {
    // *destroyed : Vue 인스턴스가 제거 되고 난 후
    },

    // 변화 속성 감지 및 캐싱
    watch: { // *watch: 주로 비동기 실행 데이터 변화 감지용
        someData: function(newVal, oldVal) {
            console.log('data changed', oldVal, '----->', newVal);
        },
    },

    computed: { //*computed: 로직을 적용한 캐싱된 속성
        ...mapGetters(['rootStoreData']), // getter - 스토어 계산 데이터 
	...mapState('module1', [ // state - 스토어 데이터
	   'inModuleData',
	]),
        reversMsg() { // 지역 계산 데이터
            return this.msg.split('').reverse().join('');
        }
     },

    // 사용되는 함수
    
    methods: { // *methods: 함수 정의
    
    	// mutations - 스토어 데이터 변이 -> 스토어 변수 상태변화
    	...mapMutations('module1', ['setData']), // 네임스페이스 사용가능
        // actions - 스토어 메소드
    	...mapActions(['fetch']),
        
        function1() {
            console.log('자식이 this.emit으로 event trigger시킴');
            //  ex) this.$emit('onFunction1'); ---- in ChildComponent
        },
        $_function2() {
            console.log('난 $가붙은 private한 함수에요 h1태그를 클릭하셨네요');
        }
    }

}
</script>

<style>
/* css 관련 영역 */ 
</style>

상태관리 라이브러리로 Vuex 사용하는 Store(모듈) 문법

vuex api 레퍼런스

import myApi from '../api/myApi'; // 사용할 API 등 import
import { Types as RootTypes } from '../rootStore'; // rootStore (메인 스토어)

// Type constants - 상수로 getters, actions, mutations 타입 관리
export const Types = {
    getters: {
        GET_IS_ERROR: 'getIsError',
    },
    actions: {
        FETCH: 'fetch',
    },
    mutations: {
        SET_DATA: 'setData',
    },
};

// *state: 데이터
const state = () => ({ // initial Data 
    data: null, // 전역 데이터
});

// *getters: store 데이터의 계산 속성 적용 (로직 적용)
const getters = {
  // 파라미터로 state, getters, rootState, rootGetters사용가능 not 객체형태
    [Types.getters.GET_IS_ERROR](state, getters, rootState, rootGetters) {
        return state.data.status.code !== 200;
    },
};

// *actions: 비즈니스 로직 실행 / 비동기적 호출 등의 로직 case
const actions = {
    // 파라미터 객체로 {dispatch, state, commit, rootState, getters, rootGetters} 사용가능
    async [Types.actions.FETCH]({ commit }) {
        //api 호출
        return new Promise((resolve, reject) => { // **dispatch: action 호출
            myApi.getData().then(resp => {
                const newData = resp.data.result;
                // **commit: mutation 호출 - 새로 받아온 데이터로 바꿔줌
                commit(Types.mutations.SET_DATA, newData);
                // options 에 root:true 를 포함하면 네임스페이스 모듈 의 root 변이에 commit 을 허용
                commit(RootTypes.mutations.SET_STATUS, 'COMPLETE', { root: true });
              
                resolve(newData);
            }).catch(err => {
                reject(err);
            });
        });
    },
};

// *mutations: 데이터 상태 변이 시킴 
const mutations = {
    // 데이터 set - 첫번째 파라미터는 state, 두번째파라미터는 넘겨받는 param 데이터
    [Types.mutations.SET_DATA](state, newData)	{
        state.data = [...newData];
    },
};

export default { // export 하여 사용가능하게 함
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};

/* 메인 스토어의 경우 모듈도 export
export default new Vuex.Store({
  modules: {
    module1,
    module2,
    ...
  },
  state,
  getters,
  actions,
  mutations
});
*/

<참고> Vuex 이점 및 아키텍쳐

profile
Junior Web FE Developer

0개의 댓글