英文:
vuejs 3 pinia unable to access data from store
问题
我第一次使用Pinia。我正在使用后端API实现登录功能,该API返回用户ID,我想将这个用户ID存储在store中,并在Vue组件中的任何地方访问它。
目前,我无法从store中访问用户ID,它不会在Vue模板中打印出用户ID。
以下是我的代码:
Sores/user.js
```js
import { defineStore } from 'pinia'
import axios from 'axios'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
userId: null,
}),
actions: {
login({ email, password }) {
axios.post('/user/login', { email: email, password: password }).then((res) => {
console.log('res', res.data.userId)
this.userId = res.data.userId
}).catch((error) => alert('error'))
},
}
})
Login.vue
<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';
const email = ref('');
const password = ref('');
const userStore = useUserStore();
const router = useRouter();
const login = () => {
userStore.login({ email: email.value, password: password.value });
router.push('/dashboard');
}
</script>
Dashboard.vue
在这里,我想从store中打印出用户ID
<template>
<div id="dashboard">
<div class="row">
<div class="col-md-4">
<Header />
{{ userStore.userId }}
</div>
</div>
</div>
</template>
<script setup>
import Header from './Header.vue';
import { useUserStore } from '@/stores/user';
const userStore = useUserStore()
</script>
<details>
<summary>英文:</summary>
I am using Pinia for the first time. I am implemeting login feature with backend api which returns userId, I want store this userId in store and want to access it anywhere in vue component.
Currently,I am not able to access the userId from store, it does not print the userId in vue template.
Here is my code:
Sores/user.js
import { defineStore } from 'pinia'
import axios from 'axios'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
userId:null ,
}),
actions: {
login({ email, password }) {
axios.post('/user/login', { email: email, password: password }).then((res) => {
console.log('res',res.data.userId)
this.userId = res.data.userId
}).catch((error)=>alert('error'))
},
}
})
Login.vue
<script setup>
import axios from 'axios';
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router';
const email = ref('');
const password = ref('');
const userStore = useUserStore();
const router = useRouter();
const login = () => {
userStore.login({ email: email.value, password: password.value });
router.push('/dashboard')
}
</script>
Dashboard.vue
here it want to print userId from store
<template>
<div id="dashboard">
<div class="row">
<div class="col-md-4">
<Header />
{{ userStore.userId }}
</div>
</div>
</div>
</template>
<script setup>
import Header from './Header.vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
</script>
</details>
# 答案1
**得分**: 2
问题出在这里:
```js
const login = () => {
userStore.login({ email: email.value, password: password.value });
router.push('/dashboard')
}
在登录之前你正在切换路由。你应该等待登录请求的响应,然后再改变路由,可以使用 async/await
:
const login = async () => {
await userStore.login({ email: email.value, password: password.value })
router.push("/dashboard")
}
或者使用 .then()
:
const login = () => {
userStore.login({ email: email.value, password: password.value }).then(() => {
router.push("/dashboard")
})
}
请注意 userStore
上的 login()
动作需要返回一个 Promise。
要么 return
axios 调用(它已经是一个 Promise):
//...
actions: {
login({ email, password }) {
return axios.post(//...
要么使用 async/await
"promisify" 动作:
//...
actions: {
async login({ email, password }) {
await axios.post(//...
英文:
The problem is here:
const login = () => {
userStore.login({ email: email.value, password: password.value });
router.push('/dashboard')
}
You're pushing the change of route before logging in. You want to wait for the login request's response, then change the route, either with async/await
:
const login = async () => {
await userStore.login({ email: email.value, password: password.value })
router.push("/dashboard")
}
... or with .then()
:
const login = () => {
userStore.login({ email: email.value, password: password.value }).then(() => {
router.push("/dashboard")
})
}
Note the login()
action on userStore needs to return a promise.
Either return
the axios call (which is already a promise):
//...
actions: {
login({ email, password }) {
return axios.post(//...
...or "promisify" the action using async/await
:
//...
actions: {
async login({ email, password }) {
await axios.post(//...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论