Honza Stínovlas
Honza Stínovlas

Reputation: 56

Share constants between Vue components

I have a collection of static data that I want to access in some of my Vue components. Example:

COLORS = Object.freeze({
    RED: 1,
    GREEN: 2,
    BLUE: 3,
})
FLAVOURS = Object.freeze({
    VANILLA: 'vanilla',
    CHOCOLATE: 'chocolate',
})

I tried to solve my problem using mixin:

// ColorMixin.js
export const COLORS = Object.freeze({
    RED: 1,
    GREEN: 2,
})

export const ColorMixin = {
    created() {
        this.COLORS = COLORS
    }
}

Then, in my component I have to use that mixin and also the constants:

<template>
    <input name="red" :value="COLORS.RED" />
    <input name="green" :value="COLORS.GREEN" />
</template>
<script>
    import {COLORS, ColorMixin} from './ColorMixin.js'
    export default {
        mixins: [ColorMixin],
        data() {
            return {
                default_color: COLORS.RED,
            }
        }
    }
</script>

This works, but it seems kind of repetitive. Is there a more elegant solution for my problem?

Upvotes: 2

Views: 5725

Answers (2)

Oli Crt
Oli Crt

Reputation: 1173

How about just using a global mixin ?

// import your constants
Vue.mixin({
  created: function () {
    this.COLORS = COLORS;
  }
})

Upvotes: 2

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 2056

You do not just import the exported var from your Color.js file into correct SFC ?

COLORS = Object.freeze({
  RED: 1,
  GREEN: 2,
  BLUE: 3,
});
FLAVOURS = Object.freeze({
  VANILLA: 'vanilla',
  CHOCOLATE: 'chocolate',
});

export {COLORS, FLAVOURS};

and then in your SFC

<template>
  <input name="red" :value="default_color" />
</template>

<script>
  import {COLORS, FLAVOURS} from './Color.js';

  export default {
    data() {
      return {
        default_color: COLORS.RED,
        default_flavour: FLAVOURS.CHOCOLATE,
      }
    }
  }
</script>

Or just create a Vuex store to save this datas and use it directly from each SFC

Upvotes: 0

Related Questions