How could I use const in vue template?
If you expose them on your data, you are making them unnecessary reactive, as @mix3d mentioned...
A better approach is to add them into Vue object Reactivity in Depth:
<template>
<div v-if="action === CREATE_ACTION">Something</div>
</template>
<script>
export default {
created() {
this.CREATE_ACTION = CREATE_ACTION;
this.UPDATE_ACTION = UPDATE_ACTION;
}
})
</script>
Expose them on your data:
new Vue({
data:{
CREATE_ACTION: CREATE_ACTION,
UPDATE_ACTION: UPDATE_ACTION
}
})
You can use plugin for this purpose as you want to include this in multiple components:
// constsPlugin.js
const YOUR_CONSTS = {
CREATE_ACTION: 1,
UPDATE_ACTION: 2
...
}
let YourConsts = {}; // As suggested by the comments.
YourConsts.install = function (Vue, options) {
Vue.prototype.$getConst = (key) => {
return YOUR_CONSTS[key]
}
}
export default YourConsts
in main.js or where you define new Vue()
, you have to use it like this:
import YourConsts from 'path/to/plugin'
Vue.use(YourConsts)
Now you can use this in a component template like following:
<div>
<select :disabled="mode === $getConst('UPDATE_ACTION')">
</div>
What about using Mixins? This is the way I do it. Not sure it is the best or recommended way but the code looks so much cleaner.
data/actions.js
export const CREATE_ACTION = 1;
export const UPDATE_ACTION = 2;
export const actionsMixin = {
data() {
return {
CREATE_ACTION,
UPDATE_ACTION
}
}
}
MyComponent.vue
<template>
<div v-if="action === CREATE_ACTION">Something</div>
</template>
<script>
import {actionsMixin, CREATE_ACTION} from './data/actions.js';
export default {
mixins: [actionsMixin]
data() {
return {
action: CREATE_ACTION
}
}
}
</script>
<template>
<div v-if="FOO_CONST.bar">Something</div>
</template>
<script>
import {FOO_CONST} from './const.js';
export default {
data() {
return {
FOO_CONST: Object.freeze(FOO_CONST) // this makes vue not reactive this data property
}
}
}
</script>