Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Emit
- sns로그인
- azure
- KAKAO
- IntelliJ
- vuex
- node.js
- v-for
- Vue.js
- mixins
- axios
- includes
- programmers
- react
- mutations
- JavaScript
- 템플릿문법
- 연동
- javscript
- v-on
- javascipt
- Login
- state
- getters
- kibana
- v-if
- Express.js
- Reduce
- 콘솔한글깨짐
- 음양더하기
Archives
- Today
- Total
공부용
[vue.js] 5. vuex 본문
0. vuex
vuex는 vue.js 애플리케이션을 위한 상태 관리 패턴 + 라이브러리이다. 상태가 예측 가능한 방식으로만 변경될 수 있도록 하는 규칙과 함께 응용 프로그램의 모든 구성 요소에 대한 중앙 집중식 저장소 역할
// 공식 url
1. 설치
npm install vuex@next --save
2. 기본세팅
2-1 ./src/assets/store.js
import { createStore } from "vuex";
export default createStore({
state: {
counter: 10
}
});
2-2
main.js
import store from "./assets/store.js" // 스토어 추가
const app = createApp(App);
app.use(store);
app.mount('#app');
2-3
./src/view/vuex.vue
<template>
<div>
counter : {{ counter }}
<br>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
</div>
</template>
<script>
export default {
data () {
return {
counter: 0
}
},
created() {
this.counter = this.$store.state.counter;
}
};
</script>
this.$store로 변수를 공유할 수 있다.
3. getters 와 mutations
위와 같이 상태를 관리하면 무분별(?)하게 된다.
그래서 getters와 mutation를 추가하여 적절하게 관리한다
./src/assets/store.js
import { createStore } from "vuex";
export default createStore({
state: {
counter: 10
},
getters: { // 상태를 가져오는 getters
getCounter: function(state) {
return state.counter;
}
},
mutations: { // 상태 동작을 하는 mutations
addCounter: function(state) {
return state.counter++;
},
subCounter: function(state) {
return state.counter--;
}
}
});
./src/view/vuex.vue
<template>
<div>
counter : {{ counter }}
<br>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
</div>
</template>
<script>
export default {
computed: {
counter() {
return this.$store.getters.getCounter;
}
},
methods: {
addCounter() {
this.$store.commit('addCounter');
},
subCounter() {
this.$store.commit('subCounter');
}
}
};
</script>
this.$store.getters를 통해 getters 안에 function을 호출하고
this.$store.commit('function')을 호출해서 값을 조작한다.
'공부용 > vue.js' 카테고리의 다른 글
[vue.js] 7. axios (0) | 2022.02.22 |
---|---|
[vue.js] 6. mixins (0) | 2022.02.21 |
[vue.js] 4. props와 emit (0) | 2022.02.21 |
[vue.js] 3-2 v-if 와 v-on (0) | 2022.02.16 |
[vue.js] 3-1. vue 템플릿 문법 및 v-for (0) | 2022.02.16 |
Comments