const : 한번 선언한 값을 변경할 수 없음(상수 개념) / 객체나 배열의 내부는 변경 가능
let : 한번 선언한 값을 다시 선언할 수 없음
ES5의 특징
변수의 Scope
ES5는 {}에 상관없이 스코프가 설정됨
Hoisting
선언한 함수와 변수를 해석기가 가장 상단에 있는 것처럼 인식함
코드의 라인 순서와 관계없이 함수선언식(function statement)과 변수를 위한 메모리 공간을 먼저 확보 함수표현식(function expression)은 해당 안됨
함수선언과 변수선언 먼저, 대입 및 할당은 나중에
Arrow Function
화살표 함수
function 키워드 대신 =>로 대체
콜백 함수의 문법을 간결화
var sum = function(a, b) {
return a + b;
};
var sum = (a, b) => {
return a + b;
};
var arr = ["a", "b", "c"];
arr.forEach(function(value) {
console.log(value);
});
arr.forEach(value => console.log(value));
Enhanced Object Literals
향상된 객체 리터럴
객체의 속성을 메소드로 사용할 때 function 예약어를 생략하고 생성 가능
var dict = {
lookup: function() {
...
}
};
var dict1 = {
lookup() {
...
}
};
npm i vuex --save
package.json 에서 확인
// 관행적으로 사용하는 폴더
src/store/store.js
Vuex 등록하기
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export const store = new Vuex.Store({
// store.js
});
// main.js에서 vue에 store를 등록
import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store/store'
createApp(App).use(store).mount('#app')
mutations : 유일하게 state 값을 변경하는 이벤트 로직, 메서드 methods
state를 변경할 때 mutations을 이용하는 이유 : 어떤 컴포넌트에서 해당 state를 변경했는지 명확하게 추적하기 위해
state: { num: 10 },
mutations: {
sumNums(state, anotherNum) {
return state.num + anotherNum;
}
}
this.$store.commit('sumNums', 20);
// mutations를 동작시킬 때 인자(payload)를 전달할 수 있음
// 인자는 한개만 전달 할 수 있으므로 두개 이상을 전달 할때는 {} 객체로
actions : 비동기 처리 로직을 선언하는 메서드 async methods
비동기 로직을 담당하는 mutations(ex.데이터 요청, Promise, ES6 async)
Q. 왜 비동기처리 로직은 꼭 actions에 선언해야 하는가?A. 시간차를 두고 여러 컴포넌트에서 state를 변경하는 경우, state 값의 변화를 추적하기 어렵기 때문에
Helper 함수
Store에 있는 속성들을 간편하게 코딩하는 방법
Helper 함수들은 인자를 명시하지 않아도 호출 단에서 인자를 넘겨줬다면 그대로 들고감 너무 신기하다...
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
... : ES6의 Object Spread Operator, 객체 속성들을 모두 가져옴
let kim = {
name: 'yoon',
lang: 'js'
};
let company = {
team: 'A',
// name: kim.name,
// lang: kim.lang
...kim
};
// 기존의 컴포넌트에 존재하는 computed속성과 mapGetters를 함께 사용하기 위해 사용함
// store.js
import * as mutations from './mutations'
export const store = new Vuex.Store({
state: {
,,,
},
mutations
});
// mutations.js
const clearItems = (state) => {
,,,
}
export { clearAllItems }
// or
export const clearItems = (state) => {
,,,
}
store의 모듈화
앱의 규모가 커서 1개의 store로 관리가 힘들때 modules속성 사용
// store.js
import todo from 'modules/todo.js'
export const store = new Vuex.Store({
modules: {
moduleA: todo, //or
todo
}
});
// todo.js
const state = {},,,