【问题标题】:vue.js and django. action, component updating, function executionvue.js 和 django。动作、组件更新、功能执行
【发布时间】:2018-08-23 08:16:46
【问题描述】:

vue.js 组件的用途

  • DataTable 组件的目的是显示后端数据库的数据。
  • NewDataPanel.vue 组件的目的是向后端数据库添加数据。

必需的行为

通过 NewDataPanel 创建新数据后,它应该出现在后端数据库和 DataTable 中。

问题

创建新数据后,它们出现在后端数据库中,但刷新 DataTable 组件时出现问题。

所需方法按顺序排列:

this.$store.dispatch('postResult')
this.$store.dispatch('getResult')

假设首先创建一些数据,然后从后端检索所有数据,并且 存储 将被变异以在 DataTable 中显示刷新的数据。

但是在添加第一个数据元素后,DataTable 没有任何反应。只有在添加第二个数据元素后,第一个才会出现在这里。

新增数据后如何实现DataTable刷新?

P.S.:源码和组件图如下。

DataTable.vue

export default {
    // ...
    computed: {
        // ...
        ...mapGetters(['resultTable'])
        // ...
    }
    // ...
    beforeMount () {
        this.$store.dispatch('getResult')
    }
}

NewDataPanel.vue

export default {
    // ...
    methods: {
        // ...
        addData () {
            // ...
            this.$store.dispatch('postResult')
            this.$store.dispatch('getResult')
            // ...
        }
        // ...
    }
    // ...
}

vuex 商店的操作通过 API 与 Django Rest Framework 配合使用:

  • postResult 只需将 JSON 发送到保存数据的后端

  • getResult 获取序列化对象列表并使用该数据改变 state.resultTable

vuex'store.js

actions = {
    getResult ({commit}, payload) {
        Result.getResult(payload).then(result => {
            commit(GET_RESULT, {result})
        })
    },
    postResult ({commit}, payload) {
        Result.postResult(payload)
    }
}

【问题讨论】:

  • this.$store.dispatch('postResult') this.$store.dispatch('getResult') 这些api调用不是同步的,你是在数据入库之前发布数据和获取数据,这就是为什么你总是落后一个getResult。请参阅 stackoverflow.com/questions/40165766/… 了解如何在函数中使用 Promise

标签: javascript django vue.js django-rest-framework vuex


【解决方案1】:

从您的代码中可以清楚地看出,您的 Result 方法返回了 Promise。你应该从你的行动中回报这个承诺。例如:

actions = {
    getResult ({commit}, payload) {
       return Result.getResult(payload).then(result => {
            commit(GET_RESULT, {result})
        })
    },
    postResult ({commit}, payload) {
        return Result.postResult(payload)
    }
}

然后您可以利用该承诺确保您的getResultpostResult 完成之前不会运行。

this.$store.dispatch('postResult')
.then(() => this.$store.dispatch('getResult'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多