[Vuejs]-VueJS DOM not updating when data does

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.

Leave a comment