【问题标题】:put a false in loading whene vuex done在 vuex 完成时加载错误
【发布时间】:2020-05-20 17:09:32
【问题描述】:

在加载中添加错误的正确方法是什么(在调度之后)?

喜欢:(我知道这行不通)

this.loading = true;
this.$store.dispatch('items', data);
this.loading = false;

<script>
    export default {

        data() {
            return {
                loading: false,
            }
        },


        methods: {

            store() {

                this.loading = true;
                this.$store.dispatch('items', data);

            },
        },
    }
</script>
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt;

【问题讨论】:

    标签: vue.js vuex vuetify.js


    【解决方案1】:

    有几种方法可以做到这一点。

    选项 1:

    Action 会返回 Promise,所以好好利用它吧。

    this.loading = true;
    this.$store.dispatch('items', data)
    .then(() => {
       this.loading = false;
    })
    

    我更喜欢这种处理方式,因为 loading 是在您使用它的地方定义和更新的。

    选项 2:

    如果您需要在多个组件之间共享loading 状态,这很有用。

    loading 放入存储状态,并在items 操作中的适当时间对其进行更新。然后你可以在你的组件中使用loading 作为$store.state.loading(或者作为一个计算属性)。

    【讨论】:

    • 我使用选项 1 但我没有看到加载。 codesandbox.io/s/j66lo
    • 第一:不要做Vue.use(axios)。从您的商店中删除该行 - 您应该通过导入库来使用 axios。一旦你解决了这个问题,你会看到记录 startend 确实有效,但是对于 loading 文本来说太快了,无法有效显示。您可以尝试在设置this.loading = false 之前设置超时,但它实际上会起作用。查看App.vuestore.js codesandbox.io/s/promiseloading-2-li4oq 中的更改
    • 我还在按钮上添加了:disabled="loading",因此在前一个请求完成之前,您无法触发新请求。
    • 为什么需要self?如果自我=这个?这样做有什么好处?
    • @Shai 如果您通过在 promise 回调中更新 this.loading 来尝试,它不起作用。基本上,回调内部的this 是高度不可预测的。通常,上下文特定于回调。您可以在回调内部和外部执行console.log(this) - 结果会有所不同。将上下文保存到单独的变量可确保您更新 vue 实例的 this
    猜你喜欢
    • 2016-03-16
    • 2020-05-19
    • 2014-09-16
    • 2023-03-08
    • 2021-10-10
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多