Home > database >  Is it possible to access variables from App.vue in other components in Vue?
Is it possible to access variables from App.vue in other components in Vue?

Time:08-09

I have an app in Vue.js where I have 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 somehow access user variable from other components? how should i export and import it in order to succeed?

CodePudding user response:

You could:

  1. Pass it down as a prop
    • Note: To mutate it from a child component you should emit an event that tells the root to update it. Don't attempt to mutate it directly in the child.
  2. Use Provide/Inject
  3. Move user to a shared state solution like Vuex or Pinia
  • Related