I can create a constant through a store in my vuejs application, but i don't think it is a good practice.what is other way to do the same?
What is the best way to create a constant, that can be accessible from entire application in VueJs ?
Asked
Active
Viewed 2.3k times
12
-
1if you don't wanna pollute the global scope, you can also use vue instace properties. Check them on the [official docs](https://vuejs.org/v2/cookbook/adding-instance-properties.html) they have some examples and explanation – zeidanbm Oct 25 '17 at 01:22
4 Answers
22
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. An example for that can be found below.
//const.js
export default {
c1: 'Constant 1',
c2: 'Constant 2'
}
// component.vue
import const from './const';
export default {
methods: {
method() {
return const.c1;
}
}
}

wegelagerer
- 3,600
- 11
- 40
- 60
6
You can use the method
const State= Object.freeze({ Active: 1, Inactive: 2 });
export default {
data() {
return {
State,
state: State.Active
};
},
methods: {
method() {
return state==State.Active;
}
}
}
or
const State= Object.freeze({ Active: 1, Inactive: 2 });
export default {
data() {
return {
State_: State,
state: State.Active
};
},
methods: {
method() {
return state==State_.Active;
}
}
}

Roohi Ali
- 628
- 6
- 7
0
try this instead
//conts.js
const test = "texte";
export default test
//component.vue
import test from "./conts";
<template>
<div>
{{example}}
</div>
</template>
export default {
data: function(){
return {
example: test
}
}
}

alpha
- 511
- 8
- 15
0
The most small big solution
//helper.js
export const Test = {
KEY1: 1,
KEY2: 2,
KEY3: 3,
KEY4: 4
}
testing the code..
//page.vue
import {Test} from "./helper";
<template>
<div>
{{testing.KEY2}}
</div>
</template>
export default {
data: function(){
return {
testing: Test
}
}
}

Darlan Dieterich
- 2,369
- 1
- 27
- 37