【问题标题】:Vuex state change not updating Vuetify tableVuex 状态更改未更新 Vuetify 表
【发布时间】:2020-09-08 06:52:18
【问题描述】:

在高层次上,父 vue 包含一个记录表和一个添加新记录的模式。 模态向父级发出回调,该父级使用新记录调用映射操作。该操作发布新记录,并提交 newRecord 突变。 newRecord 突变将新记录添加到状态记录数组中。

根据我的阅读,您必须以某种方式更新状态数组才能做出反应,我已经这样做了。但是我仍然没有看到表格更新。

父 vue

<v-data-table 
      :headers="headers" 
      :items="allRecords" 
      :items-per-page="5" 
      class="elevation-1">
...
</v-data-table>
...
computed: mapGetters(["allRecords"]),
...
methods: {
...mapActions(["getRecords", "addRecord"]),
...
created() {
    this.getRecordss();
}

记录模块*

import axios from 'axios';

const getters = {
    allRecords: state => state.records
}

const state = {
    records: []
}

const actions = {
    async getRecords({commit}){
        const response = await axios.get('/api/records')
        commit('setRecords', response.data)
    },
    async addRecord({ commit }, record) {
        const response = await axios.post('/api/records', record)
            .catch(err => console.log(err))
        commit('addRecord', response.data)
    }
}

const mutations = {
    setRecords: (state, records) => (state.records = records),
    addRecord: (state, record) => ([...state.records, record])
}

export default {
    state,
    getters,
    actions,
    mutations
}

一切都适用于帖子,刷新页面会显示新记录,但不会被动更新。

【问题讨论】:

  • this.getRecordss();移动到mounted
  • 这会导致相同的行为,除非我刷新,否则表格不会更新。
  • 您的getRecords 是异步的,您是否等待响应?
  • 我不明白。 addUser 操作使用 async/await。应该改为同步吗?

标签: vue.js vuex vuetify.js


【解决方案1】:

使用 Chrome Vue 调试插件,我发现上述突变实际上并未将新记录添加到 stores 数组。修改下面的 addRecord 突变更正了该问题。显然,传播运算符的使用不正确。

addRecord: (state, record) => ([...state.records, record])

addUser(state, user){
    state.users.push(user);
}

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2017-05-20
    • 2020-12-18
    • 2021-02-05
    • 2023-03-16
    • 2021-06-19
    • 2020-08-04
    • 2020-11-23
    • 2021-04-16
    相关资源
    最近更新 更多