国家号召后安装 pinia 商店
2022-06-30
3226
我正在使用 Composition API 构建一个 Vuejs 3 应用程序。
我有 2 个存储:一个
userStore
,用于保存用户 ID、jwt 和类似内容(登录时填充),一个
dataStore
,用于保存与用户相关的数据(用户执行操作时填充)。
当用户成功登录时,她将被重定向到包含用户数据的页面。
登录页面使用 userStore,数据页面使用 dataStore。 dataStore 需要用户的 id 和 jwt。
登录时调用此方法:
const submitlogin = async () => {
try {
const response = await postData.post('/user/a/login', {
email: form.email,
password: form.password,
})
if (response) {
userStore.loggedIn = true
// first get the jwt
userStore.getJWT()
// then go to the next page where jwt is required
router.push({
name: 'operation',
params: { sens: 'depense', quand: 'maintenant' },
})
}
} catch (error) {
console.log (error)
}
}
我 import userStore 到 dataStore:
// dataStore
import { defineStore } from 'pinia'
import { useUserStore } from '@/stores/userStore.js'
actions: {
async getAccounts(id, month, year) {
const user = useUserStore
// getData is an [axios create function][1]
getData.defaults.headers.common['__authorization__'] = user.jwt
getData.get(`/use/b/comptes/${id}/${month}/${year}`).then((response) => {
// cut because irrelevant here
}
然后,在登录后第一次:
// data view
import { useUserStore } from '../stores/userStore'
import { useDataStore } from '@/stores/dataStore'
const dataStore = useDataStore()
const userStore = useUserStore()
onMounted(() => {
dataStore.getAccounts()
})
但是,授权标头仅在第一次调用时为
undefined
。如果我进一步导航到导入 dataStore 的其他视图,则会定义
user.jwt
。
似乎 dataStore 已正确安装,但在我调用它时其状态尚不可用。
2个回答
解决了!
我更改了
dataStore
,以便 userStore 不在函数内定义,而是在导入后立即定义。
由于 getAccounts 函数是异步的,所以 user.jwt 的定义也是异步的,这有点合乎逻辑。
import { defineStore } from 'pinia'
import { getData } from '@/composables/useApi'
import { sumBy } from 'lodash'
import { useUserStore } from '@/stores/userStore.js'
// put this here, not within the async action !
const userStore = useUserStore()
actions: {
async getAccounts(id, month, year) {
getData.defaults.headers.common['__authorization__'] = userStore.jwt
getData.get(`/use/b/comptes/${id}/${month}/${year}`).then((response) => {
// cut because irrelevant here
}
thiebo
2022-07-01
我认为问题实际上是由于在操作中您没有调用 store getter,因此您尝试访问函数上的
jwt
属性,结果得到了
undefined
值。
async getAccounts(id, month, year) {
const user = useUserStore // <-------- the problem is here, () is missing
// getData is an [axios create function][1]
getData.defaults.headers.common['__authorization__'] = user.jwt
getData.get(`/use/b/comptes/${id}/${month}/${year}`).then((response) => {
// cut because irrelevant here
}
您可以在操作中调用 store getter,一切都会正常工作。事实上,这更是一种建议的方式,因为在文件根目录中调用 store getter 会增加在安装 store 之前访问它的风险,例如如果此文件将在
main.js/ts
文件中导入。
PWie
2024-05-30