1

My App.vue file:

<template>
  <v-app app color="grey">
    <Navbar v-if="isLoggedIn"></Navbar>
    <v-content class="mx-4 mb-4">
      <router-view></router-view>
    </v-content>
  </v-app>
</template>

<script>
import Navbar from "./components/Navbar";

export default {
  name: "App",
  components: { Navbar },

  data: () => {
    return {
      loggedIn: true
    };
  },
  computed: {
    isLoggedIn: () => this.data.loggedIn
  },

  mounted() {
    console.log(process.env);
  },

  created() {}
};
</script>

Loading the app in browser I got the error message :

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'data' of undefined"

Screenshot:

enter image description here

Gelin Luo
  • 13,399
  • 23
  • 77
  • 119
  • 1
    you are using arrow function which doesn't have `this` thats why `undefined` error, so you need to use **ES5** style of methods. – Lahori Apr 18 '20 at 11:06
  • The accepted answer does not work and will throw an error https://jsfiddle.net/sh0ber/nq1b74va/ – Dan Apr 18 '20 at 11:21
  • @Dan the point here is changing es6 arrow function to normal javascript function. The error is originated from my original post, my real cose is actually this: `return this.$store.state.auth.username !== null;`. Following the the approach I get my code working now. Literally your answer is more comprehensive, but kaleidawave's answer is 2m earlier than yours – Gelin Luo Apr 18 '20 at 11:31
  • @GelinLuo - There are 2 equally breaking errors in your code. `this.data` will not work in any context, arrow functions or not. Future readers who copy the syntax from that answer will have errors – Dan Apr 18 '20 at 11:33
  • @Dan makes sense. I marked your answer as accepted answer – Gelin Luo Apr 18 '20 at 11:35

2 Answers2

1

Using a arrow function creates a anonymous function which means this is bound to window and not the vue instance. Using function ensures the value of this is the vue instance. So change the isLoggedIn computed property to:

computed: {
    isLoggedIn: function() { return this.data.loggedIn }
}

// or

computed: {
    isLoggedIn() { return this.data.loggedIn }
}
kaleidawave
  • 2,054
  • 1
  • 9
  • 25
1

Change this:

computed: {
  isLoggedIn: () => this.data.loggedIn
}

to

computed: {
  isLoggedIn() {
    return this.loggedIn;
  } 
}
  • Don't use an es6 arrow function or this will lose access to the proper object. Here is a good answer on Stack Overflow about that.
  • this.data has to be used as this.$data (otherwise it's looking for a data property on the data property), but don't do that either: you actually don't need to reference data at all, and can go directly to the variable
Dan
  • 45,062
  • 13
  • 59
  • 80