다음과 같이 버튼을 눌렀을 때 1씩 Add하고 싶다.
vuex의 store
기능을 이용하기 위해 main.js에서 createStore
클래스를 import 해준다.
import { createApp } from 'vue';
import { createStore } from 'vuex';
import App from './App.vue';
const store = createStore({});
const app = createApp(App);
app.mount('#app');
const store = createStore({
state() {
return { };
}
});
const store = createStore({
state() {
return {
counter: 0
};
}
});
<template>
<base-container title="Vuex">
<h3>{{$store.state.counter}}</h3>
<button @click="addOne">Add 1</button>
</base-container>
</template>
다음과 같이 $ 사인을 붙인 store의 state를 통해 변수에 접근할 수 있다.
methods:{
addOne(){
this.$store.state.counter++;
}
},
computed:{
counter(){
return this.$store.state.counter;
}
}
TheCounter.vue에 counter를 출력하는 html과 counter를 반환하는 computed를 작성한다.
<template>
<h3>{{counter}}</h3>
</template>
<script>
export default {
computed:{
counter(){
return this.$store.state.counter;
}
}
}
</script>
<style>
</style>
App.vue에서 해당 컴포넌트를 import해주고 html로 써주기만 하면 됨
장점) props를 일일이 넘길 필요 없이 global하게 state를 사용할 수 있다.
<template>
<base-container title="Vuex">
<the-counter></the-counter>
<button @click="addOne">Add 1</button>
</base-container>
</template>
<script>
import BaseContainer from './components/BaseContainer.vue';
import TheCounter from './components/TheCounter.vue';
export default {
components: {
BaseContainer,
TheCounter,
},
computed:{
counter(){
return this.$store.state.counter;
}
},
methods:{
addOne(){
this.$store.state.counter++;
}
}
};
</script>
<style>
* {
box-sizing: border-box;
}
html {
font-family: sans-serif;
}
body {
margin: 0;
}
</style>