As a newcomer to vue.js
, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, but I'm unsure how to resolve this specific error. Any suggestions?
export default {
name: "Repaid",
components: {
VueSlideBar
},
data() {
return {
response: {},
slider: {
lineHeight: 8,
value: 2000,
data: []
},
days: {},
monthCounts: [5],
currentMonthCount: 5,
isLoading: false,
errorMessage: "",
validationError: ""
};
},
computed: {
finalPrice() {
const index = this.monthCounts.indexOf(this.currentMonthCount);
this.days = Object.keys(this.response.prices)[index]; // This line causes the side effect
const payment = this.response.prices[this.days][this.slider.value].schedule[0].amount;
}
},
I have come across suggestions to add a method like slide() to my 'days' variable in order to mutate the original object or move them into methods instead.
EDIT
I have refactored my calculations by moving them into methods and triggering a function within the computed property
. Here is the updated code:
methods: {
showPeriod() {
const index = this.monthCounts.indexOf(this.currentMonthCount);
this.days = Object.keys(this.response.prices)[index];
const payment = this.response.prices[this.days][this.slider.value].schedule[0].amount;
return "R$ " + payment;
},
},
computed: {
finalPrice() {
if (!this.response.prices || this.monthCounts === []) {
return "";
}
return this.showPeriod();
}
},