1

Could you help me understand or say if it is possible to do "circular" computed properties in Vue,

I want to divide date range into periods of certain durations, based on two criteria

  • when end date is provided interval (duration) is calculated dateRange / period
  • when interval(duration) is provided then endDate is calculated startDate + interval * period

see JSFiddle

I already try to addy second computed property for interval but it went into loop and crashed the browser.

dascorp
  • 183
  • 7
  • 15

1 Answers1

1

The recommended way of handling this is to use a computed setter. Make it so that one value is a normal data value, and the other is a computed property. Then, make it so that, when the computed property is set, it'll calculate and set the data value.

For your case, you can add a setter for endDate, then calculate interval when it's set.

  computed: {
    endDate: {
      get() {
        return moment(this.startDate).add(this.interval * this.periods, 'days')
      },
      set(value) {
        this.interval = // whatever `endDate` would end up being from setting interval directly, calculate that value here
      }
    },
  }
tony19
  • 125,647
  • 18
  • 229
  • 307
kingdaro
  • 11,528
  • 3
  • 34
  • 38
  • but this is what i did see JSFiddle i want to do calculations based on both variables either endDate or interval OR find out it is not possible. – dascorp Mar 02 '18 at 22:38
  • I looked at the fiddle and I didn't see a computed setter anywhere, like the document page I linked. I edited my answer with an example for clarity – kingdaro Mar 02 '18 at 22:46
  • More directly: no, circular computed values are not possible, as issues will arise from trying to implement them, as you've seen. Plus, in concept they just can't work. You'll run into the chicken/egg problem, where one of the values has to be calculated first, but it'll depend on the other, and so on. – kingdaro Mar 02 '18 at 22:48
  • 1
    It looks it made a trick i updated JSFiddle to reflect the change. Thank you, i also noticed browser hangs up if i do bigger dates so it seems script to be heavy lifting somewhere – dascorp Mar 02 '18 at 23:45
  • it crashes when i change startDate :( have no idea why – dascorp Mar 02 '18 at 23:58
  • If it's a different issue, best bring it to another question. – kingdaro Mar 03 '18 at 01:48