I'm facing an issue with a component that has a table row containing multiple fields. When I update one field, it triggers changes in another field based on margin or sell price.
However, monitoring all the fields results in a bouncing effect. Adding debounce somewhat mitigates the problem but doesn't fully eliminate it. In an attempt to handle this, I'm using callbacks in watchers to trigger unwatch() but when re-adding the watchers, the callbacks stop working properly.
I have included a functional gist as a code example for reference.
Vue.component('pricing', {
template: '#pricing-row',
props: ['item'],
mounted() {
this.addWatchers()
},
methods: {
resetWatchers() {
setTimeout(()=> {
this.addWatchers()
}, 700)
},
addWatchers() {
this.updateNet = this.$watch(
function() {
return this.item.net
},
function() {
// unmount other watchers
this.updateMargin()
this.updateSell()
// calculate sell price and update
this.setSellPrice()
// re-add watchers
this.resetWatchers()
}
),
this.updateMargin = this.$watch(
function() {
return this.item.margin
},
function() {
// unmount other watchers which can cause bounce effect
this.updateSell()
// calculate sell price and update
this.setSellPrice()
// re-add watchers
this.resetWatchers()
}
),
this.updateSell = this.$watch(
function() {
return this.item.sell
},
function(sellPrice) {
// unmount other watchers which can cause bounce effect
this.updateMargin()
// update margin
this.setMargin(sellPrice)
// re-add watchers
this.resetWatchers()
}
)
},
setSellPrice() {
let price = (100 / (100 - this.item.margin)) * this.item.net
this.item.sell = price.toFixed(2)
},
setMargin(sellPrice) {
let profit = (sellPrice - this.item.net)
let price = (100 * profit) / sellPrice
this.item.margin = price.toFixed(2)
}
}
})
new Vue({
el: '#vue',
data: {
prices: [
{
id: 1,
net: 5,
margin: 10,
sell: 5.56
},
{
id: 2,
net: 7,
margin: 10,
sell: 7.78
},
]
}
})
In my understanding, I believe I am utilizing the watchers correctly by mounting them on mounted()
and calling a method. Then, re-initializing by recalling that method?
Your assistance in resolving this issue would be greatly appreciated.