ILYASEM
ILYASEM

Reputation: 103

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

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?

Upvotes: 1

Views: 1212

Answers (2)

Zezombye
Zezombye

Reputation: 333

  1. $root.someVariable

Works in Vue 2, didn't test in 3.

Upvotes: 1

WillD
WillD

Reputation: 6512

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

Upvotes: 2

Related Questions