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'm working with single file components.
- I want to access those constants both in component template and in JS code (i.e. in
data()
). - I don't want them to be reactive.
- If possible, I want them to be instantiated only once (not copying each constant into each component instance).
- I don't currently use Vuex, but I'll consider it if it leads to more elegant solution.
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?