javascript vuejs 3 pinia无法从存储区访问数据

vlju58qv  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(241)

我是第一次使用Pinia。我正在用返回userId的后端API实现登录功能,我想将此userId存储在存储中,并希望在vue组件中的任何地方访问它。目前,我无法从存储中访问userId,它不会在vue模板中打印userId。以下是我的代码: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在这里它想从存储打印用户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>
zfciruhq

zfciruhq1#

问题就在这里:

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()操作需要返回一个承诺。
return axios调用(这已经是一个承诺):

//...
  actions: {
    login({ email, password }) {
      return axios.post(//...

...或使用async/await"承诺" 该操作:

//...
  actions: {
    async login({ email, password }) {
      await axios.post(//...

相关问题