'Cannot read properties of undefined Nuxt.js
I am trying to call the showMenu method on the click event based on the value passed on "open" variable.
But I m getting cannot read properties of undefined while, open is a defined variable.
I have tried to console log something on the click events it works, but whenever I try to interact with the open variable which is defined to the best of my knowledge I am getting the undefined error message.
<template>
<nav>
<div class="header-one">
<div class="header">
<div class="logo">Logo</div>
<div class="navigation" id="nav">
<nuxt-link to="/">Home</nuxt-link>
<nuxt-link to="/">About</nuxt-link>
<nuxt-link to="/">Login</nuxt-link>
<nuxt-link to="/">Logout</nuxt-link>
<nuxt-link to="/">Profile</nuxt-link>
</div>
**<div class="burger" id="burger" @click="showMenu">**
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>
<MobileMenu v-if="this.open"/>
</nav>
</template>
<script>
import MobileMenu from "~/components/MobileMenu";
export default {
name: "HeaderMenu",
MobileMenu,
data: function(){
return{
**open: false,**
}
},
methods:{
showMenu:() =>{
**this.open = !this.open**
}
}
}
</script>
Solution 1:[1]
This happen because your showMenu function is an arrow function wich change the scope of this.
Here this refer to the scope of the function instead of the components
Use a classic function instead
Here is an example
new Vue({
el: '#app',
data: () => {
return {
open: false
}
},
methods: {
toggleOpen1(){
this.open = !this.open
},
toggleOpen2: () => {
this.open = !this.open
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>Open : {{ open }}</div>
<button @click="toggleOpen1">Toggle open 1</button>
<button @click="toggleOpen2">Toggle open 2</button>
</div>
As you can see, the toggleOpen1 (classic function) methods work whereas the toggleOpen2 (arrow function), doesn't work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

