【问题标题】:How do you update VUE elements when running a promise运行 Promise 时如何更新 VUE 元素
【发布时间】:2019-07-29 08:46:44
【问题描述】:

我有一个登录屏幕,想在提交时显示一个加载元素,并在出现任何错误时停止它。

我不确定如何在 promise 解决后更新 DOM。

使用 Vue.js、Vuex 和 Vuetify。

我唯一能看到的是在 vuex 的实际状态上设置一个变量,但是如果多个加载元素使用它并且您更改状态所有加载元素都将变得可见,这将不起作用。

我尝试了很多东西,也用谷歌搜索过。但是我们从样板文件开始工作,无法真正找到与我们的用例匹配的示例。

这是我的前端代码。

<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">Login</h1>
          <p class="text-xs-center"></p>
          <ul v-if="errors" class="error-messages">
            <!-- <li v-for="(v, k) in errors" :key="k">{{ k }} {{ v | error.title }}</li> -->
            <li v-for="(v, k) in errors" :key="k">{{ v.detail }}</li>
          </ul>
          <form v-on:submit.prevent="onSubmit(email, password);">
            <fieldset class="form-group">
              <input
                class="form-control form-control-lg"
                type="text"
                v-model="email"
                placeholder="Email"
              />
            </fieldset>
            <fieldset class="form-group">
              <input
                class="form-control form-control-lg"
                type="password"
                v-model="password"
                placeholder="Password"
              />
            </fieldset>
            <v-progress-circular
              right
              :size="30"
              color="black"
              indeterminate
              v-show="isLoading"
            ></v-progress-circular>
            <button
              class="btn btn-lg btn-primary pull-xs-right"
              style="background:black; border-color:black"
            >
              Login
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { LOGIN } from "@/store/actions.type";

export default {
  name: "RwvLogin",
  data() {
    return {
      email: null,
      password: null,
      isLoading: false
    };
  },
  methods: {
    onSubmit(email, password) {
      this.isLoading = true;
      this.$store
        .dispatch(LOGIN, { email, password })
        // .then(() => this.$router.push({ name: "policies" }));
        .then(() => this.$router.push({ name: "policies" }))
        .catch((e) => {
          console.log(e);
        });
    }
  },
  computed: {
    ...mapState({
      errors: state => state.auth.errors
    })
  }
};
</script>

和模块代码:

import ApiService from "@/common/api.service";
import JwtService from "@/common/jwt.service";
import {
  LOGIN,
  LOGOUT,
  REGISTER,
  CHECK_AUTH,
  UPDATE_USER
} from "./actions.type";
import { SET_AUTH, PURGE_AUTH, SET_ERROR } from "./mutations.type";

const state = {
  errors: null,
  user: {},
  isLoading: false,
  isAuthenticated: !!JwtService.getToken()
};

const getters = {
  currentUser(state) {
    return state.user;
  },
  isAuthenticated(state) {
    return state.isAuthenticated;
  },
  isLoading(state) {
    return state.isLoading;
  }
};

const actions = {
  [LOGIN](context, credentials) {
    return new Promise(resolve => {
      ApiService.post("login", credentials)
        .then(({ data }) => {
          context.commit(SET_AUTH, data.access_token);
          resolve(data);
        })
        .catch(({ response }) => {
          if(response.status == 401){
            response.data.errors = [{"status":"401","code":0,"title":"Loginn error","detail":"The password entered is incorrect."}] 
          }
          context.commit(SET_ERROR, response.data.errors);
        });
    });
  },
  [LOGOUT](context) {
    context.commit(PURGE_AUTH);
  },
  [REGISTER](context, credentials) {
    return new Promise((resolve, reject) => {
      ApiService.post("users", credentials)
        .then(({ data }) => {
          context.commit(SET_AUTH, data.access_token);
          resolve(data);
        })
        .catch(({ response }) => {
          context.commit(SET_ERROR, response.data.errors);
          reject(response);
        });
    });
  },
  [CHECK_AUTH](context) {
    if (JwtService.getToken()) {
      // ApiService.setHeader();
      // ApiService.get("user")
      //   .then(({ data }) => {
      //     context.commit(SET_AUTH, data.access_token);
      //   })
      //   .catch(({ response }) => {
      //     context.commit(SET_ERROR, response.data.errors);
      //   });
    } else {
      context.commit(PURGE_AUTH);
    }
  },
  [UPDATE_USER](context, payload) {
    const { email, username, password, image, bio } = payload;
    const user = {
      email,
      username,
      bio,
      image
    };
    if (password) {
      user.password = password;
    }

    return ApiService.put("user", user).then(({ data }) => {
      context.commit(SET_AUTH, data.user);
      return data;
    });
  }
};

const mutations = {
  [SET_ERROR](state, error) {
    state.errors = error;
  },
  [SET_LOADING](state, loading_state) {
    state.isLoading = loading_state;
  },
  [SET_AUTH](state, token) {
    state.isAuthenticated = true;
    state.errors = {};
    state.token = token;
    JwtService.saveToken(state.token);
  },
  [PURGE_AUTH](state) {
    state.isAuthenticated = false;
    state.user = {};
    state.policies = {};
    state.errors = {};
    JwtService.destroyToken();
  }
};

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

因此,当单击提交时,它会运行与我们的 API 对话的 LOGIN 函数。这将返回错误的密码或验证错误。错误显示完美。

提交时我会做this.isLoading = true;,当它返回错误时它必须this.isLoading = false;

不知道在哪里做。

任何帮助我理解这一点都会很棒。

【问题讨论】:

    标签: javascript vue.js vuex vuetify.js


    【解决方案1】:

    你想要在这个页面加载,而不是在所有页面,所以你最好在本地管理isLoading,不需要放在vuex store中。

    例如,您可以在onSubmit 方法中将finally 添加到Promise 中,您可以取消加载状态:

    onSubmit(email, password) {
      this.isLoading = true;
      this.$store
        .dispatch(LOGIN, { email, password })
        // .then(() => this.$router.push({ name: "policies" }));
        .then(() => this.$router.push({ name: "policies" }))
        .catch((e) => {
          console.log(e);
        }).finally(() => this.isLoading = false);
    }
    

    顺便说一句,vuex 是用于global state 管理的,你不必把所有的状态都放在里面。您应该了解语言环境状态和全局状态,否则您将迷失在庞大的全局状态图中。

    对于全局状态,我认为少即是好

    【讨论】:

    • 谢谢,约翰逊李。尝试了上述方法,但没有奏效。 catch 和 finally 并没有真正采取行动。我知道本地和全球之间的区别,但有点厌倦了不让这个工作。我添加了 finally 方法,但它不起作用。
    • @JanesOosthuizen 这可能是因为您的$router.push 导致页面刷新。基本上,您执行调度并通过刷新丢失了 Promise 的跟踪,因此您无法访问 .finally 方法。在这种情况下,您应该在onSubmit() 方法的开头声明一个临时变量let doPush = false,然后在then() 语句中将其更改为true。这样做的目的是在 finally 语句中执行 $router.push,前提是您将 doPush 设置为 true。
    • @RyoShiina 你说的有道理,但如果出错,重定向不会发生。即使在删除重定向之后,finally 步骤仍然没有发生,这让我认为有些东西阻止了整个过程比“then”步骤更进一步。
    • @JanesOosthuizen 这很奇怪我同意,让我们尝试一下我们可以带来的小修复:在您的LOGIN Promise 中写一个reject(response)。这可能会解决发生错误时什么都不会发生的问题。您还需要将reject 添加为参数。
    【解决方案2】:

    所以我最终是如何通过使用全局状态变量来显示和隐藏进度并在我在后台操作项目时更新该变量来完成此操作的,请参见下面的代码。

    使用这种方法,我可以在页面上有多个进度条,并通过稍微修改代码来更新特定的进度条。

    请熟悉vue.js的朋友给点意见或指导。

    <template>
      <div class="auth-page">
        <div class="container page">
          <div class="row">
            <div class="col-md-6 offset-md-3 col-xs-12">
              <h1 class="text-xs-center">Login</h1>
              <p class="text-xs-center"></p>
              <ul v-if="errors" class="error-messages">
                <!-- <li v-for="(v, k) in errors" :key="k">{{ k }} {{ v | error.title }}</li> -->
                <li v-for="(v, k) in errors" :key="k">{{ v.detail }}</li>
              </ul>
              <form v-on:submit.prevent="onSubmit(email, password);">
                <fieldset class="form-group">
                  <input
                    class="form-control form-control-lg"
                    type="text"
                    v-model="email"
                    placeholder="Email"
                  />
                </fieldset>
                <fieldset class="form-group">
                  <input
                    class="form-control form-control-lg"
                    type="password"
                    v-model="password"
                    placeholder="Password"
                  />
                </fieldset>
                <v-progress-circular
                  right
                  :size="30"
                  color="black"
                  indeterminate
                  v-show="this.$store.getters.isLoading"
                ></v-progress-circular>
                <button
                  class="btn btn-lg btn-primary pull-xs-right"
                  style="background:black; border-color:black"
                >
                  Login
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    import { mapGetters } from "vuex";
    import { mapState } from "vuex";
    import { LOGIN } from "@/store/actions.type";
    
    export default {
      name: "RwvLogin",
      data() {
        return {
          email: null,
          password: null
        };
      },
      methods: {
        onSubmit(email, password) {
          this.$store.commit(SET_LOADING, true);
          this.$store
            .dispatch(LOGIN, { email, password })
            .then(() => this.$router.push({ name: "policies" }));
        }
      },
      mounted() {
    
      },
      computed: {
        ...mapState({
          errors: state => state.auth.errors
        })
      }
    };
    </script>
    
    import ApiService from "@/common/api.service";
    import JwtService from "@/common/jwt.service";
    import {
      LOGIN,
      LOGOUT,
      REGISTER,
      CHECK_AUTH,
      UPDATE_USER
    } from "./actions.type";
    import { SET_AUTH, PURGE_AUTH, SET_ERROR, SET_LOADING } from "./mutations.type";
    
    const state = {
      errors: null,
      user: {},
      isLoading: false,
      isAuthenticated: !!JwtService.getToken()
    };
    
    const getters = {
      currentUser(state) {
        return state.user;
      },
      isLoading(state) {
        return state.isLoading;
      },
      isAuthenticated(state) {
        return state.isAuthenticated;
      }
    };
    
    const actions = {
      [LOGIN](context, credentials) {
        return new Promise(resolve => {
          ApiService.post("login", credentials)
            .then(({ data }) => {
              context.commit(SET_AUTH, data.access_token);
              resolve(data);
            })
            .catch(({ response }) => {
              context.commit(SET_LOADING, false);
              if(response.status == 401){
                response.data.errors = [{"status":"401","code":0,"title":"Loginn error","detail":"The password entered is incorrect."}] 
              }
              context.commit(SET_ERROR, response.data.errors);
            });
        });
      },
      [LOGOUT](context) {
        context.commit(PURGE_AUTH);
      },
      [REGISTER](context, credentials) {
        return new Promise((resolve, reject) => {
          ApiService.post("users", credentials)
            .then(({ data }) => {
              context.commit(SET_AUTH, data.access_token);
              resolve(data);
            })
            .catch(({ response }) => {
              context.commit(SET_ERROR, response.data.errors);
              reject(response);
            });
        });
      },
      [CHECK_AUTH](context) {
        if (JwtService.getToken()) {
          // ApiService.setHeader();
          // ApiService.get("user")
          //   .then(({ data }) => {
          //     context.commit(SET_AUTH, data.access_token);
          //   })
          //   .catch(({ response }) => {
          //     context.commit(SET_ERROR, response.data.errors);
          //   });
        } else {
          context.commit(PURGE_AUTH);
        }
      },
      [UPDATE_USER](context, payload) {
        const { email, username, password, image, bio } = payload;
        const user = {
          email,
          username,
          bio,
          image
        };
        if (password) {
          user.password = password;
        }
    
        return ApiService.put("user", user).then(({ data }) => {
          context.commit(SET_AUTH, data.user);
          return data;
        });
      }
    };
    
    const mutations = {
      [SET_ERROR](state, error) {
        state.errors = error;
      },
      [SET_LOADING](state, status) {
        state.isLoading = status;
      },
      [SET_AUTH](state, token) {
        state.isAuthenticated = true;
        state.errors = {};
        state.token = token;
        JwtService.saveToken(state.token);
      },
      [PURGE_AUTH](state) {
        state.isAuthenticated = false;
        state.user = {};
        state.policies = {};
        state.errors = {};
        JwtService.destroyToken();
      }
    };
    
    export default {
      state,
      actions,
      mutations,
      getters
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2017-07-05
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多