0

I want to use a value in data object inside another value. When I try the code below:

data(){
   return {
      firstname: 'Shadi',
      greeting: 'hello' + firstname
   }
}

I get an error that firstname is not defined. When I use the code below:

data(){
       return {
          firstname: 'Shadi',
          greeting: 'hello' + this.firstname
       }
    }

the error is not shown but the firstname is replaced undefined. How can I solve this problem?

Shadi Farzankia
  • 639
  • 8
  • 21
  • Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Tanner Feb 24 '20 at 16:34
  • That link is for javascript; the question is about Vuejs, which does use JS but in this case it isn't the same syntax – half of a glazier Feb 25 '20 at 07:30
  • Yes syntax is different. Actually both your answers are related somehow. – Shadi Farzankia Feb 25 '20 at 07:52

1 Answers1

2

Use a computed hook:

data(){
       return {
          firstname: 'Shadi'
      }
},    
computed: {
        greeting: function () {
            return 'hello' + this.firstname;
        }
half of a glazier
  • 1,864
  • 2
  • 15
  • 45