Shadi Farzankia
Shadi Farzankia

Reputation: 737

Can't use a value of data object inside another value in vuejs

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?

Upvotes: 0

Views: 462

Answers (1)

half of a glazier
half of a glazier

Reputation: 2076

Use a computed hook:

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

Upvotes: 2

Related Questions