簡體   English   中英

如果用戶是真實的,如何使用 VUEX STORE state 在 vue.js 中將用戶重定向到主頁?

[英]How to redirect user to home page if user is authentic i.e ID or PASSWORD is correct in vue.js using VUEX STORE state?

如果用戶 ID 和密碼有效,我將在 VUEX 商店 state 中設置用戶真實性。 但是我如何在我的 signIn.vue 中訪問它來重定向?

如果用戶有效,則將 VUEX 存儲 state 即 isUserAuthentic 設置為 true 為此,我使用了計算屬性。 獲取用戶 state 即 isUserAuthentic 並在計算屬性中的 hasUserSignedIn 中解決。 我正在檢查用戶是否真實,然后重定向並從此計算屬性返回未定義。 這樣我就可以在 HTML 中使用它並且不會影響 HTML 因為我從該計算屬性返回未定義。 它正在工作,但這不是完美/最佳實踐。

登錄.vue

<template>
    <section>
        <div class="form-wrapper">

            //--------------------------------------USING COMPUTED PROPERTIES
            {{ hasUserSignedIn }}
            
            <input v-model="email"/>
            <input v-model="password"/>

            <button class="btn-signin" @click="submit()">
                sign in
            </button>
        </div>
    </section>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  data() {
     email: '',
     password: '',
  },
  methods: {
    submit() {

      if (this.email && this.password) {
        this.$store.dispatch('signInUser', { email: this.email, password: this.password });
      }
    },
    redirectTohome() {
      this.$router.push({ path: '/home' });
    },
  },

  computed: {
    ...mapGetters(['isUserAuthentic']),

    //-----------------------------------------WORKAROUND COMPUTED PROPERTIES
    hasUserSignedIn() {
      if (this.isUserAuthentic) {
        this.redirectTohome();
      }
      return undefined;
    },
  },
};
</script>

Vuex 登錄.js

import Vue from 'vue';
import axios from 'axios';

// const URL = 'http://localhost:3000';

const state = {
  signInLoading: false,
  isUserAuthentic: false,
};

const getters = {
  isSignInLoading: (signInState) => signInState.signInLoading,
  isUserAuthentic: (signInState) => signInState.isUserAuthentic,
};

const mutations = {
  SET_SIGNIN_LOADING_STATUS(signInState, status) {
    signInState.signInLoading = status;
  },
  SET_USER_AUTHENTICITY(signInState, isAuthentic) {
    signInState.isUserAuthentic = isAuthentic;
  },
};

const actions = {
  async signInUser({ commit }, payload) {
    // SET LOADING STATUS TRUE
    commit('SET_SIGNIN_LOADING_STATUS', true);

    try {
      // AUTHORIZE USER WITH AXIOS
      const response = await axios.post(`${URL}/api/v1/user/signin`, payload);

      // IF USER IS AUTHENTIC, SET AUTHENTIC STATUS TO TRUE
      if (response.status === 200) {
        commit('SET_USER_AUTHENTICITY', true);
      }
    } catch (e) {
      // SEND TOAST NOTIFICATION TO USER FOR INVALID REQUESTS
      if (e.response && e.response.data.message) {
        Vue.$toast(e.response.data.message, {
          type: 'info',
          timeout: 8000,
        });
      } else {
        Vue.$toast('Something went wrong, Please try again.', {
          type: 'error',
          timeout: 8000,
        });
      }
    }

    // SET LOADING STATUS FALSE
    commit('SET_SIGNIN_LOADING_STATUS', false);
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
};

你很准。 我覺得你應該做的唯一一件事就是你可以等待商店 dispatch('signInUser') 的 promise 解決並檢查 isUserAuthentic 的isUserAuthentic 像這樣的東西:

登錄.vue

 <script> import { mapGetters } from 'vuex'; export default { data() { email: '', password: '', }, methods: { async submit() { // use the 'async' keyword so that you can use await if (this.email && this.password) { await this.$store.dispatch('signInUser', { email: this.email, password: this.password }); // wait for the signInUser action to complete if (this.isUserAuthentic) { this.redirectTohome(); } } }, redirectTohome() { this.$router.push({ path: '/home' }); } }, }, computed: {...mapGetters(['isUserAuthentic']), // mapState will be better here since you don't alter the state }, }; </script>
 <template>... {{ isUserAuthentic }}... </template>

另外,順便說一句,我覺得你應該觸發一個提交,即commit('SET_USER_AUTHENTICITY', false); 當出現故障時。 您的代碼中缺少這一點。

由於您按原樣返回 state 而不是對其進行更改,因此在您的情況下, mapState將比mapGetters更好。

我閱讀了文檔,我認為在這種特殊情況下, WATCHERSCOMPUTED好得多。

在這種方法中,我們不必在 HTML 中使用 {{ hasUserSignedIn }}。 只需觀看該物業,當它是真實的時重定向到家。

 watch: {
    isUserAuthentic(val) {
      if (val) {
        this.redirectTohome();
      }
    },
  },

如果有人有更好的解決方案,歡迎您

暫無
暫無

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

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