Vue.js入門 - コンポーネント

Vueの基本とコンポーネント

Vue.jsの基本機能とコンポーネントの作成方法を学びます。

タスク

カウンターコンポーネント

カウントの増減ができるコンポーネントを作成します

メッセージコンポーネント

入力したメッセージを表示するコンポーネントを作成します

リストコンポーネント

アイテムを追加できるリストコンポーネントを作成します

ヒント

Vue.jsのコンポーネントを作成し、データバインディングを実装しましょう。

参考コード

// カウンターコンポーネント
const CounterComponent = {
  template: `
    <div class="counter">
      <div class="counter-title">カウンター</div>
      <div class="counter-value">{{ count }}</div>
      <button @click="increment">+1</button>
      <button @click="decrement">-1</button>
    </div>
  `,
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    }
  }
}

// メッセージコンポーネント
const MessageComponent = {
  template: `
    <div class="counter">
      <div class="counter-title">メッセージ</div>
      <input v-model="message" placeholder="メッセージを入力">
      <div class="counter-value">{{ message }}</div>
    </div>
  `,
  data() {
    return {
      message: ''
    }
  }
}

// リストコンポーネント
const ListComponent = {
  template: `
    <div class="counter">
      <div class="counter-title">リスト</div>
      <ul>
        <li v-for="item in items" :key="item.id">
          {{ item.text }}
        </li>
      </ul>
      <button @click="addItem">アイテムを追加</button>
    </div>
  `,
  data() {
    return {
      items: [
        { id: 1, text: 'アイテム1' },
        { id: 2, text: 'アイテム2' }
      ]
    }
  },
  methods: {
    addItem() {
      const newId = this.items.length + 1
      this.items.push({ id: newId, text: `アイテム${newId}` })
    }
  }
}

// アプリケーションの作成
const app = Vue.createApp({
  components: {
    'counter-component': CounterComponent,
    'message-component': MessageComponent,
    'list-component': ListComponent
  }
})

// マウント
app.mount('#app')

プレビュー

見本