Werner
Werner

Reputation: 309

TypeError: Cannot set property of undefined

need some support.

I want to show data by click a button or link

<div v-for="hpTheme in hpThemes" :key="hpTheme.id">
      <button class="button round success" @click="showDetails(hpTheme.id)">{{hpTheme.hpTitle 
}}</button>
</div>


<script>
export default {
 data() {
  return {
   hpTheme: { hpTitle: '', hpContent: '' },

  hpThemes: [
    {
      id: 1,
      hpTitle: 'title',
      hpContent: 'content'
    },
    {
      id: 2,
      hpTitle: 'title2',
      hpContent: 'content2'
    } 
   ]
 }
},
methods: {
showDetails(id) {

  for (var i = 0; i <= this.hpThemes.length; i++) {

    if (id === this.hpThemes[i].id) {
      this.theme.hpTitle = this.hpThemes[i].hpTitle
      this.theme.hpContent = this.hpThemes[i].hpContent
    }
   }
  }
}
</script>

But I get this error: TypeError: Cannot set property 'hpTitle' of undefined. How to solve? Thanks for support.

Upvotes: 0

Views: 1555

Answers (3)

Amaarockz
Amaarockz

Reputation: 4674

I have just changed the this.theme to this.hpTheme below. Hope this works for you.

showDetails(id) {
  for (var i = 0; i <= this.hpThemes.length; i++) {
    if (id === this.hpThemes[i].id) {
      this.hpTheme.hpTitle = this.hpThemes[i].hpTitle
      this.hpTheme.hpContent = this.hpThemes[i].hpContent
    }
   }
  }

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

@WilliamWang's answer is perfect to remove that error, but your code be more clean and shorter if you just pass the clicked theme as parameter then assign it to this.theme :

@click="showDetails(hpTheme)"

and

methods: {
  showDetails(theme) {
    this.hpTheme={hpTitle: theme.hpTitle, hpContent: theme.hpContent }
  }
}

Upvotes: 2

wangdev87
wangdev87

Reputation: 8751

variable i shouldn't equal to the this.hpThemes.length

for (var i = 0; i < this.hpThemes.length; i++) { // replace '<=' operator with '<'
   ...
}

Upvotes: 2

Related Questions