Can Vue components access variables in App.vue?
P粉491421413
P粉491421413 2024-01-06 09:54:21
0
2
386

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粉491421413
P粉491421413

reply all(2)
P粉549412038
  1. $root.someVariable

Works in Vue 2, not tested in 3.

P粉488464731

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template