【问题标题】:Adding delay after vuex state changes在 vuex 状态更改后添加延迟
【发布时间】:2020-11-22 12:15:57
【问题描述】:

当值 - v-if 指令绑定到 - 从 true 更改为 false 时,我试图添加一些延迟来过渡到元素。我正在使用Vuex来维护isLoading的状态,以便在其他组件中使用。

所以我有一个 API 调用,在等待响应时将 this.$store.state.isLoading 设置为 true,一旦收到响应则设置为 false。但问题是 API 响应几乎是即时的,进度条只闪烁一瞬间。

<template>
  <div>
    <b-progress v-if="isLoading" :max="max">
      <b-progress-bar :value="count"></b-progress-bar>
    </b-progress>
  </div>
</template>

<script>
module.exports = {
    data() {
        return {
            count: 0,
            max: 100
        }
    },
    computed: {
        isLoading () {
            return this.$store.state.isLoading;
        }
    }
}
</script>

在状态改变后添加延迟是正确的想法吗?如果是这样,正确的做法是什么?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    假设您有一个名为 updateIsLoading 的突变来更新 isLoading 状态,您应该在 API 调用之后立即添加延迟。

    fetch(url)
      .then(res => res.json())
      .then(res => {
        // do something with your data
        setTimeout(() => this.$store.commit('updateIsLoading'), 1000)
      })
      .catch(...)
    

    如果您需要一劳永逸地设置延迟,一种解决方案是创建一个动作,然后在您从 API 调用获得响应后调度该动作。

    actions: {
      updateIsLoading({ commit }) {
        setTimeout(() => commit('updateIsLoading'), 1000)
      }
    }
    

    如果您真的想在您的组件中执行此操作,您可以设置一个观察程序并在延迟一段时间后更新一个本地 isLoading 变量:

    export default {
        data() {
            return {
                count: 0,
                max: 100,
                isLoading: false
            }
        },
        computed: {
            loading () {
                return this.$store.state.isLoading;
            }
        },
        watch: {
          loading(newVal, oldVal) {
            setTimeout(() => this.isLoading = newVal, 1000)
          }
        }
    }
    

    【讨论】:

    • 但是我的 api 调用位于多个其他组件中。我正在尝试为所有人使用相同的加载器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 2021-01-10
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多