Home > Article > Web Front-end > Why Do Arrow Functions Break Vue Computed Properties, and How Can I Fix Them?
Use Arrow Functions in Vue Computed Properties: Troubleshooting
In Vue, computed properties are used to derive reactive values from other properties. While arrow functions can simplify code in many scenarios, they can be problematic when used in computed properties.
Original Code (Working):
new Vue({ el: '#app', data: { turnRed: false, turnGreen: false, turnBlue: false }, computed: { switchRed: function () { return { red: this.turnRed }; }, switchGreen: function () { return { green: this.turnGreen }; }, switchBlue: function () { return { blue: this.turnBlue }; } } });
Modified Code (Not Working):
However, when you modify the methods in computed properties using arrow functions, the behavior changes:
computed: { switchRed: () => { return { red: this.turnRed }; }, switchGreen: () => { return { green: this.turnGreen }; }, switchBlue: () => { return { blue: this.turnBlue }; } }
Explanation:
The root cause of this issue is that arrow functions do not bind this to the Vue instance. Instead, they inherit the context of the parent scope. In this case, the parent scope is the global scope, so this refers to the window object, rather than the expected Vue instance. Consequently, the turnRed, turnGreen, and turnBlue values remain uninitialized, leading to unchanging colors.
Solution:
To resolve this issue and make arrow functions work in computed properties, Vue recommends using the bind method to explicitly bind this to the Vue instance:
computed: { switchRed: () => { return { red: this.turnRed }; }.bind(this), switchGreen: () => { return { green: this.turnGreen }; }.bind(this), switchBlue: () => { return { blue: this.turnBlue }; }.bind(this) }
The above is the detailed content of Why Do Arrow Functions Break Vue Computed Properties, and How Can I Fix Them?. For more information, please follow other related articles on the PHP Chinese website!