ブログの投稿ログ

2021年
9月
8月
7月
6月

VueXでTodoアプリ 01

Vueを久しぶりに書いてみました。
今日は入力ボックスへ文字列を入れて、エンターキーを押した時にLISTへ移動させる挙動を書いていきます。


今日のコード

codesandbox


vue側


<template>
  <div id="todo">
    <div class="wrap">
      <h2>Todo Input</h2>
	## エンターキーを押したらaddTodoTexが実行される
      <input type="text" @keyup.enter="addTodoText" />
    </div>
    <div class="wrap">
      <h2>Todo List</h2>
      <ul>
	## idとtextをtodosから受け取る
        <li v-for="(todo, key) in todos" :key="key">
          <p>ID : {{ todo.id }}</p>
          <p>Text : {{ todo.text }}</p>
          <button @click="doneTodo(todo.id)">Done</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
  components: {},

  computed: {
 // Vuexのstoreへアクセス
    todos: function () {
      return this.$store.state.todos;
    },
 // Vuexのstoreへアクセス
    dones: function () {
      return this.$store.state.dones;
    },
  },

  methods: {
 // 入力欄でエンターを押したら
    addTodoText: function (e) {
 // 入力欄で入力した値を取得
      var text = e.target.value;
  // storeへ渡す
      this.$store.dispatch("addTodo", {
        text: text,
      });
      e.target.value = "";
    },
  },
};
</script>

Vue側の処理はこちらになります。 入力欄で入力された値はエンターキーを押すことで、storeへ送られるようになっています。

store側

// vuexを定義
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
// 状態を保持する値をステートとして設定
  state: {
    todos: [],
    dones: []
  },

  actions: {
    addTodo(context, todo) {
      context.commit("ADD_TODO", todo.text);
    },
    done(context, todo) {
      context.commit("DONE_TODO", todo.id);
    },
    reset(context, todo) {
      context.commit("RESET_TODO", todo.id);
    }
  },

// 内部ロジックを指定
  mutations: {
    ADD_TODO(state, text) {
      var todo = {
        id: 0,
        text: text
      };
      if (state.todos.length !== 0) {
        todo.id = state.todos[state.todos.length - 1].id + 1;
      }
      state.todos.push(todo);
    }
  }
});

export default store;

以上になります。