Home  >  Q&A  >  body text

Can Vue components access variables in App.vue?

I have an application in Vue.js, and in it there is an App.vue like this:

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',

 data() {
    return {
      user: null,
    }
  },

  methods: {
       getUser() {
        axios 
        .get(`auth/user/`)
        .then(response => {
          this.user=response.data.pk
        })
      }
  },

  beforeMount() {
    this.getUser();
  },
}
</script>

Can I access user variables from other components somehow? How should I export and import it successfully?

P粉491421413P粉491421413286 days ago340

reply all(2)I'll reply

  • P粉549412038

    P粉5494120382024-01-07 00:36:37

    1. $root.someVariable

    Works in Vue 2, not tested in 3.

    reply
    0
  • P粉488464731

    P粉4884647312024-01-07 00:23:39

    you can:

    1. Pass it as prop
      • Note: To change it from a child component, you should emit an event telling root to update it. Don't try to mutate it directly in the offspring.
    2. Use Provide/Inject
    3. Move users to a shared state solution such as Vuex or Pinia

    reply
    0
  • Cancelreply