Fix this is Undefined in Vue
Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.
In this article, we’ll look at how to fix the ‘this is undefined’ error in Vue apps.
How to the Error Shown?
We may or may not get an error message saying ‘this is undefined’. We might just see that the variables that we expected to update didn’t update.
How to fix “this is undefined”?
The cause of the ‘this is undefined’ error is probably caused by using arrow functions when we try to reference this
in our component object.
Arrow functions do not bind to this
, which we need to access the Vue component instance.
For instance, if we have the following code:
index.js
:
new Vue({
el: "#app",
data: {
text: "foo"
},
methods: {
toggle: () => {
this.text = this.text === "foo" ? "bar" : "foo";
}
}
});
index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<button @click="toggle">Toggle</button>
<p>{{text}}</p>
</div>
<script…