Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

vuex2.xその0001 公式ドキュメントにあるカウンターアプリを作ってみる

参考にさせて頂いたページ

公式ドキュメント

ソースコード

はじめに

色々な事情でwebpackなどを使用できない環境下でスタンドアローンビルドのvuexを使用するような想定で書いています。

サンプルソースコード

例として以下の通りです。 storeにはstrict: true,を設定した方が良さそうだなと思っています。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="">
</head>
<body>

<div id="app">
</div>

<script src="js/vue.js"></script>
<script src="js/vuex.js"></script>
<script>
/**
 * store
 */
const store = new Vuex.Store({
  strict: true,
  state: {
    count: 0
  },
  mutations: {
    increment: state => state.count++ ,
    decrement: state => state.count-- ,
  }
});

/**
 * Counterコンポーネント
 */
const Counter = {
  template: `
    <div>
      <div>{{ count }}</div>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </div>
  `,
  computed: {
    count(){ return this.$store.state.count; },
  },
  methods: {
    increment({commit}) {
      this.$store.commit('increment')
    },
    decrement({commit}) {
        this.$store.commit('decrement')
    }
  }
};

/**
 * rootコンポーネント
 */
const app = new Vue({
  el: '#app',
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter />
    </div>
  `
});
</script>

</body>
</html>