Home > Enterprise >  Access application variable from a component in vue?
Access application variable from a component in vue?

Time:10-18

I know this question may be duplicated or asked several times. But I'm so new in Vue and I'm not able to find a clear question. How can I read/write a variable from the app into the components? All I see around they are passing values from the parent component into the child component. This seems like is not working in this case. This is the structure of my app, I would like to keep this structure.

let app = Vue.createApp({
    components:['contrib'],
    data(){
        return{
            contButton:"first value",
        }
    },
    methods: {
        someMethods:{
        },
    },
})


app.component('contrib',{
    props:['contButton'],
    template: `
    <div>
        <button  id="myBtn" @click="showCont">{{contButton}}</button>
    </div>
    `,
    data(){
        return{
            newCont:null,
        }
    },
    methods:{
            showCont() {
            this.newCont=this.contButton
            console.log(this.newCont)
        },
    }
})  


app.mount('#app')

CodePudding user response:

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

CodePudding user response:

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>

  • Related