Apply global variable to Vuejs

前端 未结 8 1408
谎友^
谎友^ 2020-12-02 15:02

I have a javascript variable which I want to pass globally to Vue components upon instantiation thus either each registered component has it as a property or it can be acces

相关标签:
8条回答
  • 2020-12-02 15:53

    A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY. I did like that:

    Supposing that I have 2 global variables (var1 and var2). Just add to the index.html header this code:

      <script>
          function getVar1() {
              return 123;
          }
          function getVar2() {
              return 456;
          }
          function getGlobal(varName) {
              switch (varName) {
                  case 'var1': return 123;
                  case 'var2': return 456;
                  // ...
                  default: return 'unknown'
              }
          }
      </script>
    

    It's possible to do a method for each variable or use one single method with a parameter.

    This solution works between different vuejs mixins, it a really global value.

    0 讨论(0)
  • 2020-12-02 15:55

    If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

    0 讨论(0)
提交回复
热议问题