【问题标题】:Vuex reactivity problem for list inside nested object嵌套对象内列表的Vuex反应性问题
【发布时间】:2021-03-08 13:49:29
【问题描述】:

我正在尝试使用 vuex 创建调度程序应用程序。为了实现调度,我使用了一个名为“scheduleController”的状态属性,它是一个对象,如下所示。

const state = {
    scheduleController: {
    2020: {
        11: {
            month: "November",
            count: [{
                days: [],
                timers: [{
                    from: null,
                    interval: null,
                    to: null
                }]
            }]
        }
        12: {
            month: "December"
            ...
        }
    }
}
}

每当我按下添加按钮时,计时器数组应该添加另一个与第一个对象相同的对象,以便在选定的日期为该月创建多个计划。为此,我使用了以下突变:

addTimer: (state, indices) => {
    let timer = {
        from: null,
        to: null,
        interval: null,
    };  
    //indices[0] gives the year and indices[1] gives month-index 
    //and indices[2] gives the nth element of count array in which
    //an empty timer has to be added. 
    Vue.set(state.scheduleController[indices[0]][indices[1]].count[indices[2]].timers, 1, timer)
}

状态会按我的意愿改变,但它不是反应式的。我必须获得另一个视图,然后再回来查看状态的变化。如何使其具有反应性?

在上面的代码中,我曾经使用过

state.scheduleController[indices[0]][indices[1]].count[indices[2]].timers.push(timer)

代替 Vue.set 函数。但是看了这个链接后,我把它改成了现在的样子,但还是不行。谢谢。 https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    解决了

        addTimer: (state, indices) => {
            let timer = {
                from: null,
                to: null,
                interval: null,
            };
    
    
        let newScheduleController = JSON.parse(JSON.stringify(state.scheduleController))
    
        newScheduleController[indices[0]][indices[1]].count[indices[2]].timers.push(timer)
    
        state.scheduleController = newScheduleController
    
        },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 2018-11-29
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多