Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create a constant, that can be accessible from entire application in VueJs ?

Tags:

vue.js

vuex

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?

like image 609
Mukund Kumar Avatar asked Oct 23 '17 06:10

Mukund Kumar


2 Answers

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;
    }
  }
}
like image 107
wegelagerer Avatar answered Oct 19 '22 12:10

wegelagerer


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;
    }
  }
}
like image 6
Roohi Ali Avatar answered Oct 19 '22 12:10

Roohi Ali