我在 Vue.js 中有一個(gè)應(yīng)用程序,其中有一個(gè)像這樣的 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>
我可以以某種方式從其他組件訪問用戶變量嗎?我應(yīng)該如何導(dǎo)出和導(dǎo)入它才能成功?
$root.someVariable
在 Vue 2 中工作,未在 3 中測(cè)試。
你可以:
用戶
移至共享狀態(tài)解決方案,例如Vuex或Pinia