← Back
vue

Using constants and functions in vue components

I've learned that you can't access things not defined in the Vue component instance.

For example, you can't import a constant or a function and use it in the template:

This doesn't work

<template>
<button></button>
</template>

<script>
import { BUTTON_LABEL } from 'i18n'

export default {
...
}
</script>

Expose constants #

It seems that the best way to expose constants is by defined in the created lifecycle method to avoid Vue applying it's observable sorcery on it:

<template>
<button>{{ label }}</button>
</template>

<script>
import { BUTTON_LABEL } from "i18n";

export default {
created() {
this.label = BUTTON_LABEL;
},
};
</script>

Expose utility functions #

The same happens with functions:

This doesn't work

<template>
<select :options="getUserOptions(user)">
</template>

<script>
import { getUserOptions } from 'helpers/userHelpers'

export default {
...
}
</script>

But this does:

<template>
<select :options="getUserOptions(user)">
</template>

<script>
import { getUserOptions } from 'helpers/userHelpers'

export default {
methods: {
getUserOptions,
}
...
}
</script>