I tried to defined a const
in a *.vue
file:
<script>
export const CREATE_ACTION = 1,
export const UPDATE_ACTION = 2
<script>
And use them in the template:
<template>
...
<select :disabled="mode === UPDATE_ACTION">
....
</template>
But it does not work. How can I use const
in a Vue template?
To define common constants in Vue. js, we can create a module that export an object with the constant values. const DELIVERY = "Delivery"; const CARRIER = "Carrier"; const COLLATION = "Collation"; const CASH_AND_CARRY = "Cash and carry"; export default { DELIVERY, CARRIER, COLLATION, CASH_AND_CARRY, };
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
You can always define a variable outside of the Vue app scope and use it throughout the application. However, if you are using any bundler like Webpack/Browserify/etc. you can do the same but you'd have to import it into every component using it.
The const keyword is used to create a constant in Vue. js.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With