【问题标题】:How Can I change the value of a property in a component by a Vuex store action?如何通过 Vuex 存储操作更改组件中属性的值?
【发布时间】:2020-12-01 06:40:04
【问题描述】:

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

例如,在这个 if 里面:

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));
},

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuex


    【解决方案1】:

    我在我的应用程序中这样做的方式是在 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('/');
            }
        }
    }
    

    【讨论】:

    • 我喜欢你的做法。出于好奇,您是否希望在 try-catch 中捕获任何特定错误,或者 try-catch 是 .catch(error) 的 async/await 等价物吗?
    • 技术上它会捕获 try 块内的任何错误,因为我使用的是 async-await 语法,所以它不仅等同于 .catch(error),而且如果在调用 router.replace() 时出现错误
    【解决方案2】:

    将一个名为error 的属性添加到您的状态并在 axios 请求回调中更新:

    login({commit, dispatch}, userInfo){
        axios.post('/login', userInfo)
        .then(response => {
            if (response.status === 401) {
                console.log('Error logging in');
                commit('setError',true);
            } else {
                commit('authUser', {
                    token: response.data.token,
                    userId: response.data.userId,
                    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;
            }
       }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2019-09-01
      • 2019-06-17
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多