[Vue] Vue란?

[Vue] Vue란?

Vuex로 해결 할 수 있는 문제

  1. MVC 패턴에서 발생하는 구조적 오류
  2. 컴포넌트 간 데이터 전달 명시
  3. 여러 개의 컴포넌트에서 같은 데이터를 업데이트 할 때 동기화 문제

Vuex 개념

  1. State : 컴포넌트 간에 공유하는 데이터 data()
  2. View : 데이터를 표시하는 화면 template
  3. Action : 사용자의 입력에 따라 데이터를 변경하는 methods


Vuex 구조

Component -> async logic -> sync logic -> state
state : 여러 컴포넌트에 공유되는 데이터data
getters : 연산된 state 값을 접근하는 속성 computed
mutations : state 값을 변경하는 이벤트 로직, 메서드 methods
actions : 비동기 처리 로직을 선언하는 메서드 aysnc methods

State

  • state가 변경되면 자연스럽게 뷰 리액티비티에 의해서 화면이 다시 갱신됨
// Vue
data: {
    message: 'hi vue'
}

// Vuex
state: {
    message: 'hi vue'
}
-----------------------------------------
// vue
{{ message }}



// vuex
{{ this.$store.state.message }}

Getter

  • state값에 접근한다.
  • computed()처럼 미리 연산된 값에 접근한다
// store.js
state: {
    num: 10
},
getters: {
    getNumber(state) {
        return state.num;
    },
    doubleNumber(state) {
        return state.num * 2;
    }
}

------------------------------------

<p>{{ this.$store.getters.getNumber }}</p>
<p>{{ this.$store.getters.doubleNumber }}</p>


Mutations

  • state값을 변경할 수 있는 유일한 메서드
  • commit()으로 동작시킨다
//store.js
state: { num: 10 },
mutations: {
  printNumbers(state) {
    return state.num
  },
  sumNumbers(state, anotherNum) {
    return state.num + anotherNum;
  }
}

//App.vue
this.$store.commit('printNumbers');
this.$store.commit('sumNumbers', 20);
commit() : state를 변경하기 위해 mutations를 동작시킬 때 인자(payload)를 전달할 수 있다
// store.js
state: { storeNum: 10 },
mutations: {
  modifyState(state, payload) {
    console.log(payload.str);
    return state.storeNum += payload.num;
  }
}

// App.vue
this.$store.commit('modifyState', {
  str: 'passed from payload',
  num: 20
});

mutations으로 state를 변경하는 이유

  • 여러개의 component에서 아래처럼 state값을 변경하면 추적하기가 어렵다
methods: {
  increaseCounter() { this.$store.state.counter++; }
}
  • 특정 시점에 어떤 컴포넌트가 state를 접근하여 변경한 건지 확인하기 어려움
  • 뷰의 반응성을 거스르지 않게, 명시적으로 상태 변화를 수행하여 반응성, 디버깅, 테스팅 혜택을 얻는다


Action

  • 비동기 처리 로직을 선언하는 메서드
  • 비동기 처리(데이터 요청, Promise, async)는 모두 actions 선언
// store.js
state: {
  num: 10
},
mutations: {
  doubleNumber(state) {
    state.num * 2;
  }
},
actions: {
  delayDoubleNumber(context) { // context로 store의 메서드와 속성 접근
    context.commit('doubleNumber');
  }
}

//App.vue
this.$store.dispatch('delayDoubleNumber');

  • 비동기 로직을 actions에 선언 해야하는 이유
    • 언제 어느 컴포넌트에서 해당 state를 호출하고, 변경했는지 확인이 어렵기 때문

example
// store.js
mutations: {
  setMenuData(state, fetchedData) {
    state.menu = fetchedData;
  }
},
actions: {
  fetchMenuData(context) { // context로 store의 메서드와 속성 접근
    return axios.get('https://abel.com/menu/1')
                .then(response => context.commit('setMenuData', response));
  }
}

//App.vue
methods: {
  getMenu() {
    this.$store.dispatch('fetchMenuData');
  }
}


Vue 프로젝트 구조

  • asset : 외부에서 가지고 온 이미지, 파일, css, js파일 등을 넣어두는 폴더
  • router : 서버사이드에서 제공하는 라우팅을 사용하지 않아도 라우팅을 할 수 있도록 도와주는 것
    • 이것을 통해서 페이지를 서버에 요청하지 않아도 새로운 페이지로 이동 가능
  • main.js : 프로젝트의 base파일.
    • 전역 설정을 하려면 main.js을 수정하면 됨

전역 & 지역 컴포넌트

Global Component

  • 컴포넌트를 뷰 인스턴스에 등록해서 사용할 때 다음과 같이 global 하게 등록 할 수 있다
Vue.component('my-component', {
   // ...
})

Local Component

var cmp = {
    data: function () {
        return {
            // ...
        };
    },
    template: '',
    methods: {}
}
 // 아래 Vue 인스턴스에서만 활용할 수 있는 로컬(지역) 컴포넌트 등록
new Vue({
    components: {
        'my-cmp': cmp
    }
})

출처

댓글

이 블로그의 인기 게시물

[Python] # -*- coding: utf-8 -*-를 쓰는 이유

[소프트웨어공학] NS(Nassi-Schneiderman) 차트

[컴퓨터네트워크] Telnet이란?