首頁  >  問答  >  主體

Vue 元件可以存取 App.vue 中的變數嗎?

我在 Vue.js 中有一個應用程序,其中有一個像這樣的 App.vue:

<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>

我可以以某種方式從其他元件存取使用者變數嗎?我應該如何匯出和匯入它才能成功?

P粉491421413P粉491421413286 天前339

全部回覆(2)我來回復

  • P粉549412038

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

    1. $root.someVariable

    在 Vue 2 中工作,未在 3 中測試。

    回覆
    0
  • P粉488464731

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

    你可以:

    1. 將其作為 prop 傳遞
      • 注意:要從子元件更改它,您應該發出一個事件告訴 root 更新它。不要嘗試直接在子代中對其進行突變。
    2. 使用提供/注入
    3. #將使用者移至共享狀態解決方案,例如VuexPinia

    回覆
    0
  • 取消回覆