如何通过Vuex存储操作更改组件中属性的值?

问题描述

我有一个Login视图,其中包含一个登录表单和一个函数,该函数调度名为login的Vuex存储操作。此操作发出了一个POST请求,我想知道是否可以将在error视图内找到的Login属性更改为Vuex存储中分派的操作内部的某种内容

例如,在此情况下,如果:

if (response.status === 401) {
    console.log('Error logging in')
}

我想将error属性的值更改为true。有可能吗?

<template lang="html">
    <div class="register">
        <div class="register-container">
            <p>Welcome back!</p>
            <form @submit.prevent="onSubmit" novalidate>
                <div class="margin-bottom-20">
                    <p>Email</p>
                    <input v-model='email' type='email'>
                </div>
                <div class="margin-bottom-20">
                    <p>Password</p>
                    <input v-model='password' type="password">
                </div>
                <div v-if='error'>Error</div>
                <button type="submit" name="button">Continue</button>
            </form>
        </div>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    data(){
        return {
            email: '',password: '',error: false
        }
    },methods: {
        onSubmit(){
            let userInfo = {
                password: this.password,email: this.email
            }
            this.$store.dispatch('login',userInfo)
        }
    }
}
</script>

这是在Vuex存储中找到的登录操作。

login({commit,dispatch},userInfo){
    axios.post('/login',userInfo)
    .then(response => {
        if (response.status === 401) {
            console.log('Error logging in')
        } else {
            commit('authUser',{
                token: response.data.token,userId: response.data.userId,username: response.data.username
            })
            router.replace('/')
        }
    }).catch((error) => console.log(error));
},

解决方法

我在应用中执行此操作的方式是在vuex操作上返回axios响应对象,然后让组件检查响应对象

例如:

// I'm gonna use async-await syntax since it's cleaner
async login({commit,dispatch},userInfo){
    try {
        const response = await axios.post('/login',userInfo)
        if (response.status == 401) {
            commit('authUser',{
                token: response.data.token,userId: response.data.userId,username: response.data.username
            })
            router.replace('/')
        }
        return response;
    } catch (err) {
        console.log(error)
    }
},

在您的组件上:

methods: {
    async onSubmit(){
        let userInfo = {
            password: this.password,email: this.email
        }
        const response = await this.$store.dispatch('login',userInfo);
        if (response.status === 401) {
            this.error = true;
        } else {
            // This is optional since you already handling the router replace on the vuex actions
            // However i would put the replace on here instead of in vuex action since vuex actions should only contain logic for component state.
            this.$router.replace('/');
        }
    }
}
,

在状态中添加一个名为error的属性,并在axios请求回调中进行更新:

login({commit,userInfo){
    axios.post('/login',userInfo)
    .then(response => {
        if (response.status === 401) {
            console.log('Error logging in');
            commit('setError',true);
        } else {
            commit('authUser',username: response.data.username
            })
         commit('setError',false);
            router.replace('/')
        }
    }).catch((error) => commit('setError',true));
},

并在组件中将error属性作为计算出的值:

   data(){
        return {
            email: '',password: '',}
    },computed:{
      error(){
        return this.$store.state.error;
        }
   }