Vue.js 3 Pinia 无法从 store 中访问数据

huangapple go评论102阅读模式
英文:

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)=&gt;alert(&#39;error&#39;))
},

}
})


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

    &lt;div class=&quot;col-md-4&quot;&gt;
       
        &lt;Header /&gt;
        {{ userStore.userId }}

    &lt;/div&gt;

    &lt;/div&gt;
&lt;/div&gt;

</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 = () =&gt; {
  userStore.login({ email: email.value, password: password.value });
  router.push(&#39;/dashboard&#39;)
}

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 () =&gt; {
  await userStore.login({ email: email.value, password: password.value })
  router.push(&quot;/dashboard&quot;)
}

... or with .then():

const login = () =&gt; {
  userStore.login({ email: email.value, password: password.value }).then(() =&gt; {
    router.push(&quot;/dashboard&quot;)
  })
}

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(//...

huangapple
  • 本文由 发表于 2023年2月27日 17:36:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定