LoginSignup
0
1

[Vue3] composable の使い方

Last updated at Posted at 2024-01-28

はじめに

  • 記事の概要
    Vue3 内でのcomposableの使い方の備忘録
    基本的には公式ドキュメントをみれば大丈夫
  • 対象
    すでにVue3環境の動作が可能なユーザー
  • 記事執筆の背景
    コンポーネント内のコード量が気になったので、composableを使用して対象の変数、対象の関数をまとめて管理した

実現したいこと

  • 複数のコンポーネント内で使用されるリアクティブ変数とリアクティブ変数を制御する変数を別ファイルで管理する。

開発環境

下記のモジュールをインストールする。

package.json
"devDependencies": {
    "@mdi/font": "^7.4.47",
    "@storybook/addon-essentials": "^7.6.7",
    "@storybook/addon-interactions": "^7.6.7",
    "@storybook/addon-links": "^7.6.7",
    "@storybook/blocks": "^7.6.7",
    "@storybook/test": "^7.6.7",
    "@storybook/vue3": "^7.6.7",
    "@storybook/vue3-vite": "^7.0.2",
    "@vitejs/plugin-vue": "^4.0.0",
    "axios": "^1.6.5",
    "laravel-vite-plugin": "^0.7.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "sass": "^1.26.5",
    "sass-loader": "^8.0.2",
    "storybook": "^7.0.2",
    "swiper": "^11.0.5",
    "vite": "^4.0.0",
    "vue": "^3.2.47"
  }

セットアップ

  • 開発環境のセットアップ方法
    管理しやすくするために以下のエイリアスを追加
vite.config.js内
resolve: {
        alias: {
          "@composables": fileURLToPath(new URL("./resources/js/composables", import.meta.url)),
        },
    },

使い方

使い方

  • 1.composable ファイルの作成
resource/js/composable/useActiveIndex.js
import { ref, watch } from 'vue'
// note activeIndexは現在何ページ目にいるかのページ数 
// goNextPage goPreviousPage はページの行き来のための変数 buttonにイベントを紐づけて使用
// nextPage , previousPageはページの移動が可能であるかを計算するフラグ

export function useActiveIndex(length) {
  const activeIndex = ref(0)
  const nextButtonFlag = ref(false);
  const previousButtonFlag = ref(false);
  nextPage()
  previousPage()
  watch([activeIndex], () => {
    nextPage();
    previousPage();
  });


  function goNextPage() {
    if (!(activeIndex.value + 1 > length - 1)) {
      activeIndex.value += 1;
    }
  }
  function goPreviousPage() {
    if (!(activeIndex.value - 1 < 0)) {
      activeIndex.value -= 1;
    }
  }
  function nextPage() {
    var flag = true;
    if ((activeIndex.value + 1 > length - 1)) {
      flag = false;
    }
    nextButtonFlag.value = flag;
  }
  function previousPage() {
    var flag = true;
    if ((activeIndex.value - 1 < 0)) {
      flag = false;
    }
    previousButtonFlag.value = flag;
  }

  return { activeIndex,nextButtonFlag,previousButtonFlag,goNextPage,goPreviousPage }
}
  • 2.composableを使用するページ
resource/js/component/test.vue
import { useActiveIndex } from '@composables/useActiveIndex.js'
const {activeIndex,nextButtonFlag,previousButtonFlag,goNextPage,goPreviousPage} = useActiveIndex(mockProps.length);
0
1
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
0
1