3
3

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 3 years have passed since last update.

Nuxt Composition APIでシンプルなToDoリストを作る[TypeScript]

Last updated at Posted at 2021-09-03

はじめに

Nuxt.jsで Composition API を使う新しい方法であるNuxt Composition API(@nuxtjs/composition-api)を使ってシンプルなToDoリストを作ります。

Nuxt Composition APIとは

Nuxt Composition APIとは、Nuxt.jsの次期バージョンである、Nuxt 3のための実験的なパッケージです。

Note: the main aim is to allow experimentation and feedback before the final release of Nuxt 3. The API of Nuxt-specific methods will likely change before Nuxt 3 is released.
(Google Translate) 注:主な目的は、Nuxt 3の最終リリースの前に実験とフィードバックを可能にすることです。Nuxt固有のメソッドのAPIは、Nuxt3がリリースされる前に変更される可能性があります。

npmでは、@nuxtjs/composition-apiとして提供されています。

NuxtでComposition APIを使う方法は2つあります。@vue/composition-apiを使う方法と、今回紹介する@nuxtjs/composition-apiを使う方法です。
今回はより新しい方法である、@nuxtjs/composition-apiを試してみます。

Nuxt Composition APIの最新バージョンはv0.27.0です。 v1にも満たないパッケージなので本番環境で使うのは少し早いかもしれません。

セットアップ

Nuxtインストール

mkdir simple-todo
cd simple-todo
yarn create nuxt-app 

流れに沿ってインストールするが今回はTypeScriptを選択する

Composition APIをセットアップ

yarn add @nuxtjs/composition-api

nuxt.config.jsに以下を追加

{
  buildModules: [
    '@nuxt/typescript-build',
+    '@nuxtjs/composition-api/module'
  ]
}

完成イメージ

Sep-02-2021 21-29-42.gif

コード

pages/index.vue
<template>
  <div>
    <ul>
      <li v-for="(todo, index) in todos">
        <input type="checkbox" v-model="todo.done"/>
        <span>{{ todo.title }}</span>
        <button @click="remove(index)">REMOVE</button>
      </li>
    </ul>
    <input type="text" v-model="newToDoTitle"/>
    <button @click="add">ADD</button>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref} from "@nuxtjs/composition-api";

type ToDo = {
  done: boolean,
  title: string
}

export default defineComponent({
  head: {
    title: 'My Page'
  },
  setup() {
    const todos = ref<ToDo[]>([
      {
        done: false,
        title: 'これはやることです'
      }, {
        done: true,
        title: '二つ目のやること'
      }, {
        done: false,
        title: '三つ目のやること'
      },
    ])
    const newToDoTitle = ref<string>('')
    const add = () => {
      todos.value.push(
          {
            done: false,
            title: newToDoTitle.value
          }
      )
      newToDoTitle.value = ''
    }
    const remove = (index: number) => {
      todos.value.splice(index, 1);
    }

    return {
      todos,
      newToDoTitle,
      add,
      remove
    }
  }
})
</script>

終わり

参考になりましたら幸いです

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?