Apply global variable to Vuejs

前端 未结 8 1415
谎友^
谎友^ 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:34

    You can use a Global Mixin to affect every Vue instance. You can add data to this mixin, making a value/values available to all vue components.

    To make that value Read Only, you can use the method described in this stackoveflow answer.

    Here is an example:

    // This is a global mixin, it is applied to every vue instance. 
    // Mixins must be instantiated *before* your call to new Vue(...)
    Vue.mixin({
      data: function() {
        return {
          get globalReadOnlyProperty() {
            return "Can't change me!";
          }
        }
      }
    })
    
    Vue.component('child', {
      template: "
    In Child: {{globalReadOnlyProperty}}
    " }); new Vue({ el: '#app', created: function() { this.globalReadOnlyProperty = "This won't change it"; } });
    
    
    In Root: {{globalReadOnlyProperty}}

提交回复
热议问题