Apply global variable to Vuejs

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

    In VueJS 3 with createApp() you can use app.config.globalProperties

    Like this:

    const app = createApp(App);
    
    app.config.globalProperties.foo = 'bar';
    
    app.use(store).use(router).mount('#app');
    

    and call your variable like this:

    app.component('child-component', {
      mounted() {
        console.log(this.foo) // 'bar'
      }
    })
    

    doc: https://v3.vuejs.org/api/application-config.html#warnhandler

    If your data is reactive, you may want to use VueX.

提交回复
热议问题