# Nuxt.js でフロントエンドのカテゴリ選択

環境

  • Nuxt.js 2.x
  • Vue.js 2.x

Vuex Store のセットアップ

export const state = () => ({
  categories: [], // カテゴリデータ
  selectedCategories: [], // 選択されたカテゴリ
});

export const mutations = {
  setCategories(state, categories) {
    state.categories = categories;
  },
  setSelectedCategories(state, selectedCategories) {
    state.selectedCategories = selectedCategories;
  },
};

export const actions = {
  async fetchCategories({ commit }) {
    const categories = await this.$axios.$get("/api/categories"); // 仮のAPIエンドポイント
    commit("setCategories", categories);
  },
};

# カテゴリコンポーネントの作成

<template>
  <div>
  <!-- 選択されたカテゴリー -->
    <ul class="list-unstyled text-muted">
      <li class="d-inline pointer" @click="resetCategory">
        Top
        <font-awesome-icon icon="fa-angle-right" class="mx-1" />
      </li>
      <li
        v-for="(c, index) in selectedCategory"
        :key="'selectedCategory' + c.id"
        :class="`d-inline ${selectedCategory.length > index + 1 && 'pointer'}`"
      >
        <font-awesome-icon
          icon="fa-angle-right"
          v-if="index > 0"
          class="mx-1"
        />
        <span @click="handleCategory(c, index)">
          {{ c.name }}
        </span>
      </li>
    </ul>
    <!-- カテゴリ選択 -->
    <ul class="list-unstyled ms-3">
      <li
        v-for="c in descendants"
        :key="'selectCategory' + c.id"
        :class="`${
          selectedId == c.id && 'fw-bold'
        } text-start text-decoration-none pointer`"
        @click="handleCategory(c)"
      >
        {{ c.name }}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  props: {
    open: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.descendants = this.stateCategories
  },
  data() {
    return {
      display: this.open,
      parentId: 0,
      selectedId: 0,
      selectedCategory: [], // 選択したカテゴリー配列
      descendants: [], // 表示カテゴリー
      selectDone: false,
    }
  },
  computed: {
    stateCategories() {
      return this.$store.state.app.categories
    },
  },
  watch: {
    open(value) {
      this.display = value
      this.resetCategory()
    },
  },
</script>

一部割愛しますが、最初に親カテゴリーの一覧を表示して、クリックしたら選択したカテゴリーの子の一覧を表示する仕組みです。

2024-02-12
  • nuxtjs