What is the best way to create a constant, that ca

2020-04-05 07:12发布

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?

标签: vue.js vuex
3条回答
兄弟一词,经得起流年.
2楼-- · 2020-04-05 07:50

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;
    }
  }
}
查看更多
Melony?
3楼-- · 2020-04-05 07:53

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;
    }
  }
}
查看更多
劳资没心,怎么记你
4楼-- · 2020-04-05 08:04

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
  }
 }
}
查看更多
登录 后发表回答