LoginSignup
8
2

More than 1 year has passed since last update.

【Script SetUp】当日のタスクだけを表示させたい!【VUEX】【TypeScript】

Last updated at Posted at 2022-10-29

始めに

当日のタスクのみを表示するページの実装を行います!

やることはたった2つ!

  • 事前準備(データを作っておく)
  • データの加工

開発環境

  • MacBook Air (M1, 2020)
  • npm 8.18.0
  • "dayjs": "^1.11.5"
  • "vue": "^3.2.13"
  • "vuex": "^4.0.0"

事前準備

検索機能を実装する前にやることが2つあります。
①型定義
②取得するデータの設定

型定義

使用する型を作りましょう。

src/types/index.ts
export type State = {
  todos: todo[];
};

export type Todo = {
  id: number;
  description: string;
  date: Date;
};

検索するデータの設定。

以下のコードでは2つのことをします。

  • 取得するデータ設定
  • ゲッターでデータを取得するコードを定義
src/store/index.ts
import { InjectionKey } from 'vue';
import { createStore, Store, useStore as baseUseStore } from "vuex";
import { State } from '../types'

export const key: InjectionKey<Store<State>> = Symbol();

export const store = createStore<State>({
  //データの設定
 state: {
    todos: [
        //当日のタスクのみ表示されているか確認するため、一つだけ、違う日程にしておく。
        {
            id:1,
            description: 'プログラミング'
            date: '2022-10-29'
        },
        {
            id:2,
            description: '散歩'
            date: '2022-10-29'
        },
        {
            id:3,
            description: '筋トレ'
            date: '2022-10-30'
        }
    ],
  },
    //データ取得するゲッターの定義
  getters: {
     getTodos: state => state.todos
  },
  mutations: {
  },
  actions: {
  }
});

export const useStore = () => {
  return baseUseStore(key);
}

データの加工

ゲッターで取得したデータに、当日の日程を含むもののみ表示する処理を行います。
手順は2つ。
①dayjsのインストール
②データの加工

dayjsのインストール

ターミナルで以下を実行してください。

npm install dayjs --save

データの加工

+以下のファイルにinjectしてください。

src/views/TodosView.vue
<script setup lang="ts">
import { computed } from 'vue'
import { useStore } from '../store'
import { Todo } from '../types'
import dayjs from 'dayjs'

//現在の日付を取得。リアクティブにすることで、常に当日の日付となる。
const currentDate = ref(dayjs())

//元々定めた日付のフォーマットの形に加工する。
const displayDate = computed(()=>{
    return currentDate.value.format('YYYY-MM-DD')
})

const store = useStore()
//当日の日付を含むデータのみを取ってくるようにゲッターを定義。
const todos = computed<Todo[]>(()=>{
    return store.getters['getTodos'].filter((element: Todo)=>todo.date.toString().includes(displayDate.value))
    )
})

</script>
<template>
    <div>
        <h2>当日のタスク一覧</h2>
        <hr />
        <table>
            <thead>
                <th>タスク</th>
                <th>日時</th>
            </thead>
            <tbody>
                <tr v-for="todo in todos" :key="todo.id">
                    <td>{{todo.description}}</td>
                    <td>{{todo.date}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>
8
2
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
8
2