当状态改变时,基于 vuex 状态的计算属性不会触发观察者

时间:2021-03-11 17:21:53

标签: vue.js vuex

我有两个组成部分:销售额和数量。在每个组件中都有一个 DateRange 组件,它允许用户选择一个日期范围。

有两种显示模式:通用模式,其中更改一个组件中的日期范围不会影响另一个组件。单一模式,其中更改 Sales 中的日期范围应更改 Quantity 组件中的日期范围。

DateRange 组件基于 v-calendar 提供一个漂亮的日历,然后通过计算属性 dateRange 我可以将 v-calendar 中选定范围的开始和结束日期解析为我可以使用的格式(YYYY-MM-DD) 在后端)。

为了实现 SalesQuantity 组件之间的这种同步,我使用带有 product_custom_range 的 Vuex 存储,以防单一模式(通过 prop调用 singleProduct) 被激活然后使用存储中的值,否则只需解析所选范围并返回它。因此,如果 store 中的值发生变化,那么两个组件中的计算属性都会发生变化。

但是,当 DateRange 组件中的此计算属性发生更改时,我还需要发出一个事件,但观察者不工作,即使 dateRange 属性在两个组件中都成功更改

注意: dateRange 是计算属性,range 只是 data 中定义的 v-calendar 使用的局部状态变量

代码如下:

computed: {
    dateRange: function(){
        let dateRangeObj = {}
        
        if(this.singleProduct){
            dateRangeObj = this.$store.state.product_custom_range
        }
        else{
            if(this.range != null){
             dateRangeObj["start"] = moment(this.range.start).format("YYYY-MM-DD")
             dateRangeObj["end"] = moment(this.range.end).format("YYYY-MM-DD")
            }

        }
    
        console.log("Date range ",dateRangeObj)
        console.log("From store: ",this.$store.state.product_custom_range)
        
        return dateRangeObj
        
    }
},
methods:{
    selectRange(){
        console.log(this.dateRange)
        
        if(this.singleProduct){
            let dateRangeObj = {
                start: moment(this.range.start).format("YYYY-MM-DD"),
                end: moment(this.range.end).format("YYYY-MM-DD")
            }
            this.$store.commit("changeProductCustomRange",dateRangeObj)
            
        }
        
        
        this.$emit("dateRangeSelected",this.dateRange)
    }

观察者现在只是一个简单的,应该记录“观察者正在工作”:

    dateRange:{
        handler: function(o,n){
            console.log("Date range changed")
        },
        deep: true
    }

这里是存储中的突变和初始值的代码:

export default new Vuex.Store({
  state: {
    product_custom_range:{},
  },
  mutations: {
    changeProductCustomRange(state,payload){
        // Used to synchrnize custom ranges
        state.product_custom_range["start"] = payload.start
        state.product_custom_range["end"] = payload.end
    }
  }
})

0 个答案:

没有答案