0

Computed name property of a component is undefined

<template>
  <div class="person">
    <p>{{name}}</p>
  </div>
</template>

<script>
  export default {
    name: 'person',
    data () {
      return {
        firstName: 'John',
        lastName: 'Doe',
      }
    },
    computed: {
      name: () => {
        return `${this.firstName} ${this.lastName}`
      }
    }
  }
</script>

results in undefined undefined

Jocky Doe
  • 2,041
  • 4
  • 17
  • 28

1 Answers1

0

I already have a similar problem because computed had to have a setter and a getter like this :

  computed: {
    fullName: {
      // getter
      get: function () {
       return this.firstName + ' ' + this.lastName
     },
     // setter
     set: function (newValue) {
       var names = newValue.split(' ')
       this.firstName = names[0]
       this.lastName = names[names.length - 1]
     }
   }
}
alex
  • 132
  • 4
  • 4
    Creating a setter/getter isn't what solved your problem it is because you created a regular function (`function(){}`) instead of an arrow function (`()=>{}`) which doesn't have it's own `this` – Patrick Evans Jun 14 '18 at 21:22
  • @PatrickEvans can a context be bound to an arrow function? – Jocky Doe Jun 14 '18 at 21:28
  • @JockyDoe no, the `thisArg` argument will be ignored when attempting to use `bind`, `call`, etc – Patrick Evans Jun 14 '18 at 21:54