[Vuejs]-Access application variable from a component in vue?

0๐Ÿ‘

If You want to:

  1. Share data from parent to child use props or maybe emitting custom events.
  2. Create an app-level shared state use Pinia or Vuex
  3. Share data between components use Event Bus

0๐Ÿ‘

As both the component are in a same page, I am assuming both are having sibling relationship. If Yes, You can give a try to below approach :

  • Pass the variable from Component 2 to the parent via emitting an event.
  • Now, after capturing the variable, You can pass that variable as a prop in Component 1.

Live Demo (Just for understanding, I am using Vue 2, You can change it as per your Vue version) :

Vue.component('component1', {
  props: ['variable', 'childmsg'],
  template: '<p>{{ childmsg }}</p>',
  mounted() {
    setTimeout(() => {
        console.log(this.variable)
    })
  }
});

Vue.component('component2', {
  data(){
    return{
      variable2: '123'
    }
  },
  mounted() {
    this.$emit('component-2-variable', this.variable2)
  },
  props: ['childmsg'],
  template: '<p>{{ childmsg }}</p>'
});

var app = new Vue({
  el: '#app',
  data: {
    component2Var: null
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <component1 :variable="component2Var" childmsg="This is Component 1"></component1>
  <component2 @component-2-variable="component2Var = $event" childmsg="This is Component 2"></component2>
</div>

Leave a comment