How to access property inside object defined in data using this keyword

Imagine there a object listed on data propery like this:

data(){
 return {
  fruit: {
   grape: {
    purpleGrape: {
      price: '$5',
      showPrice: () => { console.log(this.fruit.grape.purpleGrape.price) }
    },
    greenGrape: {
    ....
    }
   }
  }
 }
}

is that another way to simplify the showPrice function that use this.fruit.grape.purpleGrape.price to get the price instead ? I want to use this keyword that refers to the object it belongs to like :

showPrice: () => this.price

But it doesnt work, I just want to simplify this nested thingy → this.fruit.grape.purpleGrape.price

Hi @argaWirawan1234-tech. If my understanding is right you just wanted to check the price without always digging to this.fruit.grape.purpleGrape.price

you could use computed and just call showPrice in your .vue file

  {
   return {
    fruit: {
     grape: {
      purpleGrape: {
        price: '$5'
      },
      greenGrape: {
      }
     }
    }
   }
  },
  computed: {
    showPrice () {
      return this.fruit.grape.purpleGrape.price
    } 
  }```

Hope this helps :slightly_smiling_face:
1 Like

data should not contain functionality but data only.

I assume you’d want to have the showPrice functionality as a part of your fruits. You can make this reference via the way you include it in your template

<template>
  <ul class="grapes-list" v-for="(grape0, name) in fruit.grape">
    <li class="grape-item" @click="showPrice(grape0)">{{name}}</li>
  </div>
</template>

And then in your component you have a method for that.

{
 data(){ ...your data... },
 ...,
 methods: {
    showPrice(fruit){
      console.log("showing price", fruit.price)
    }
 }
}

Sidenote: I’d suggest to have your data use the plural like fruits (not fruit) and grapes (not grape) so that you can use the singular of those when you refer to a single child object of those data keys.