0

So I have a simple example with a button and some text but for some reason, it's not updating even though when I log the Vue object, data is clearly being updated.

<template>
  <div>
    <span>{{ showNav }}</span>
    <span class="parallax__nav__trigger" v-on:click="toggleNav">
        Menu 
    </span>
  </div>
</template>

<script>
export default {
    data: () => ({
      showNav: false,
    }),
    methods: {
      toggleNav: () => {
        this.showNav = !this.showNav
        console.log(this)
      }
    }
  }
</script>
...
Nathan Horrigan
  • 763
  • 1
  • 9
  • 20

1 Answers1

4

Mind the this when declaring functions:

export default {
    data: () => ({
      showNav: false,
    }),
    methods: {
      toggleNav: () => {
        this.showNav = !this.showNav
        console.log(this)
      }
    }
}

Should be:

export default {
    data() {                                   // <== changed this line
      showNav: false,
    },
    methods: {
      toggleNav() {                            // <== changed this line
        this.showNav = !this.showNav
        console.log(this)
      }
    }
}

Reasoning

Don't use arrow functions (() => {}) when declaring Vue methods. They pick up the this from the current scope (possibly window), and will not reflect the Vue instance.

From the API Docs:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.

tony19
  • 125,647
  • 18
  • 229
  • 307
acdcjunior
  • 132,397
  • 37
  • 331
  • 304