vue 两个相互依赖的计算属性 [英] vue two computed properties depending on each other
问题描述
你能帮我理解或说是否可以在 Vue 中做循环"计算属性,
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
- 当
end date
被提供时interval (duration)
被计算dateRange/period
- 当提供了
interval(duration)
时,计算endDate
startDate + interval * period
- when
end date
is providedinterval (duration)
is calculateddateRange / period
- when
interval(duration)
is provided thenendDate
is calculatedstartDate + interval * period
参见 JSFiddle
我已经尝试为 interval
添加第二个计算属性,但它进入循环并导致浏览器崩溃.
I already try to addy second computed property for interval
but it went into loop and crashed the browser.
推荐答案
推荐的处理方式是使用 计算 setter.使一个值是正常数据值,另一个是计算属性.然后,设置为当设置了计算属性时,它会计算并设置数据值.
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.
对于您的情况,您可以为 endDate
添加一个 setter,然后在设置时计算 interval
.
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
}
},
}
这篇关于vue 两个相互依赖的计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!