Sometimes, we want to fix Vue.js computed properties not working with arrow functions.
In this article, we’ll look at how to fix Vue.js computed properties not working with arrow functions.
How to fix Vue.js computed properties not working with arrow functions?
To fix Vue.js computed properties not working with arrow functions, we should replace arrow functions with regular functions so that this is set to the Vue component.
For instance, we write
export default {
//...
computed: {
switchRYellow() {
return { red: this.turnYellow };
},
switchGreen() {
return { green: this.turnGreen };
},
switchBlue() {
return { blue: this.turnBlue };
},
},
//...
};
to add the switchRYellow, switchGreen and switchBlue computed properties to regular functions.
Then we use properties from this where this is the current Vue component instance.
this.turnYellow, this.turnGreen and this.turnBlue are reactive properties.
Conclusion
To fix Vue.js computed properties not working with arrow functions, we should replace arrow functions with regular functions so that this is set to the Vue component.