Apply global variable to Vuejs

2019-02-05 15:37发布

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 accessed globally.

Note:: I need to set this global variable for vuejs as a READ ONLY property

3条回答
Root(大扎)
2楼-- · 2019-02-05 15:51

You can use mixin and change var in something like this.

// This is a global mixin, it is applied to every vue instance
Vue.mixin({
  data: function() {
    return {
      globalVar:'global'
    }
  }
})

Vue.component('child', {
  template: "<div>In Child: {{globalVar}}</div>"
});

new Vue({
  el: '#app',
  created: function() {
    this.globalVar = "It's will change global var";
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
  In Root: {{globalVar}}
  <child></child>
</div>

查看更多
做自己的国王
3楼-- · 2019-02-05 16:07

Just Adding Instance Properties

For example, all components can access a global appName, you just write one line code:

Vue.prototype.$appName = 'My App'

$ isn't magic, it's a convention Vue uses for properties that are available to all instances.

Alternatively, you can write a plugin that includes all global methods or properties.

查看更多
▲ chillily
4楼-- · 2019-02-05 16:13

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
Vue.mixin({
  data: function() {
    return {
      get globalReadOnlyProperty() {
        return "Can't change me!";
      }
    }
  }
})

Vue.component('child', {
  template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});

new Vue({
  el: '#app',
  created: function() {
    this.globalReadOnlyProperty = "This won't change it";
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
  In Root: {{globalReadOnlyProperty}}
  <child></child>
</div>

查看更多
登录 后发表回答