0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue.js Vuexで状態を管理する (値の設定)

Posted at

前回(https://www.mkhs.work/wordpress2/?p=213)では storeで設定した値を返すサンプルを作成しました。今回は値を設定するサンプルです。値の管理はstore側で実施していますので、store.jsに設定します。counterを増やすサンプルです。mutationsを定して、counterを増やす、クリアするオブジェクト定義をします。

import { createStore } from 'vuex'
export const store = createStore({
state() {
return{
message: 'store dataです!!',
counter: 0,
}
},
mutations: {
count_plus: (state) => {
state.counter++
},
count_reset:(state) => {
state.counter = 0
}
},
})

store.jsを呼び出すコンポーネントのサンプルです。

<template>
  <div class="alert alert-primary">
    <p> {{ $store.state.message }}</p>
  </div>
  <div class="btn btn-secondary" v-on:click="$store.commit('count_plus')" v-on:ctrl="$store.commit('count_reset')">
    <a class="h5">
      clicked: {{ $store.state.counter }}
    </a>
  </div>
</template>
<script>
import {reactive} from 'vue'
export default {
setup(){
const data = reactive({
})
return {
data
}
}
}
</script>

ブラウザで動作確認します。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/146872/1378fdae-7418-31f1-5ed2-f86f676a0889.png)

値は永続化されていないので、リロードするとゼロにクリアされます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?