B
B
BonBon Slick2020-05-13 20:02:13
typescript
BonBon Slick, 2020-05-13 20:02:13

Best way to use Vue + TypeScript constants?

import {ANIME_LIST_NAME, GALLERY_NAME} from '@/router/urls';
import {Component, Vue} from "vue-property-decorator";

@Component({
    components: {},
})
export default class Home extends Vue {
    public ANIME_LIST_NAME: string = ANIME_LIST_NAME;
    public GALLERY_NAME: string = GALLERY_NAME;


It works, BUT, it makes the constants reactive as I understand it.
There is another option to use as a mixin with methods from which we return constants or a plugin, which is also not very good because then you need to do a plugin for the constants of each module
import constPlugin from "./components/constPlugin";
Vue.use(constPlugin);

the plugin describes the logic

here is a piece of methods from the mixin
public animeListName(): string {
        return ANIME_LIST_NAME;
    }

    public galleryName(): string {
        return GALLERY_NAME;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-05-15
@BonBonSlick

Why make them properties of an instance? Just use in methods.
If there is some text in the "constants" - you can use vue-i18n, so that both the text is in one place and the translation, if you can quickly file it.
If you don't want to complicate things, you can always shove constants or an object with text into Vue.prototype.
Regarding reactivity - yes, they will be reactive, but you won't change them.) To be sure - just add readonly and typescript won't let you touch them. If you want completely without reactivity, then you can manually put them in the created or beforeCreate hook in this.
Regarding mixins - in order to add them, you don't need plugins, just put them in an array

@Component({
    mixins: [],
})
And you don't need extra "getX" methods, we don't have Java here.) You can also mixin data, you can protect it from changes and reactivity through Object.freeze().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question