簡體   English   中英

如何通過 Vuex 存儲操作更改組件中屬性的值?

[英]How Can I change the value of a property in a component by a Vuex store action?

我有一個Login視圖,其中包含一個登錄表單和一個 function ,它調度一個名為login的 Vuex 存儲操作。 此操作發出一個POST請求,我想知道是否可以將Login視圖中的error屬性更改為 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 響應 object,並讓組件檢查響應 object

例如:

// 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('/');
        }
    }
}

在 state 中添加一個名為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;
        }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM