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
  • "vue": "^3.2.13"

事前準備

検索機能を実装する前にやることが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-28'
        },
        {
            id:3,
            description: '筋トレ'
            date: '2022-10-30'
        }
    ],
  },
    //データ取得するゲッターの定義
  getters: {
     getTodos: state => state.todos
  },
  mutations: {
  },
  actions: {
  }
});

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

検索機能実装!

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

//リアクティブなデータを作成
const todoFilter = ref('')

const store = useStore()
//打ち込んだものを含むデータを取ってくるようにする。
const todos = computed<Todo[]>(()=>{
    return store.getters['getTodos'].filter((element: Todo)=> 
        element.description.includes(todoFilter.value)|| 
        //includesはDate型だと使えないので、string型に変える。
        element.date.toString().includes(todoFilter.value)
    )
})

</script>
<template>
    <div>
        <h2>タスク一覧</h2>
        <form>
            <label>
                検索したいキーワードを入力してください<br>
                <input type="text" v-model="todoFilter"/>
            </label>
        </form>
        <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>

終わり

検索機能は意外と簡単に実装できちゃいます。
includes()メソッドは結構使えるのでぜひ覚えて帰っちゃってください!

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