Vue.jsで定数をコンポーネント外のファイルで一括管理する方法【Vue2】

環境

Vue:2.6.11

内容

Vue.jsで、どのコンポーネントからでも呼び出し可能な定数を定義したいとき、コンポーネント外のjsファイルで一括管理することができます。

1. script内で定数を使用したい場合

srcの下にconsts/const.jsを作成します。

src/consts/const.js

export default Object.freeze({
  SAMPLE_VALUE:"テストバリュー",
});

Object.freezeを使用することで、外部で値を書き換え不可にできます。

コンポーネント側で呼び出します。

src/views/sample.vue

<template>
  <div>
    <button @click="test">
      テストボタン
    </button>
  </div>
</template>
<script>
import constant from "@/consts/const";
export default {
  methods: {
    test(){
      console.log(constant.SAMPLE_VALUE);
    }
  }
}
</script>

import constant from "@/consts/const" でconst.jsを読み込みます。

constant.SAMPLE_VALUE で定数にアクセスします。

テストボタンを押下するとコンソールにSAMPLE_VALUEの値が表示されます。

constant.SAMPLE_VALUEの値を書き換えようとするとエラーが出て書き換え不可となっています。

methods: {
    test(){
      console.log(constant.SAMPLE_VALUE);
      constant.SAMPLE_VALUE = "代入";
    }
  },

2.template内で定数を使用したい場合

const.jsを読みこむためのjsファイルをmixinに作成します。

src/mixins/constLoad.js

export default function(constants) {
  return {
    created: function() {
      for (const [key, value] of Object.entries(constants)) {
        this[key] = value;
      }
    }
  };
}

コンポーネント側です。

src/views/sample.vue

<template>
  <div>
    <button @click="test">
      テストボタン
    </button>
    <span>
      {{constant.SAMPLE_VALUE}}
    </span>
  </div>
</template>
<script>
import constant from "@/consts/const";
import constLoad from "@/mixins/constLoad";
export default {
  methods: {
    test(){
      console.log(constant.SAMPLE_VALUE);
    }
  },
  mixins: [constLoad({ constant })]
}

import constLoad from "@/mixins/constLoad でconstLoadを読み込み、

mixins: [constLoad({ constant })] でconstLoadの引数にconstantを渡します。

定数の値を画面に表示することができました。