开发者问题收集

类型错误:无法设置未定义的属性

2020-11-06
1495

需要一些支持。

我想通过点击按钮或链接显示数据

<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>

但我收到此错误:TypeError:无法设置未定义的属性“hpTitle”。 如何解决? 谢谢支持。

3个回答

变量 i 不应等于 this.hpThemes.length

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

@WilliamWang 的答案可以完美地消除该错误,但是如果您仅将单击的主题作为参数传递,然后将其分配给 this.theme ,您的代码会更干净,更简短:

@click="showDetails(hpTheme)"

methods: {
  showDetails(theme) {
    this.hpTheme={hpTitle: theme.hpTitle, hpContent: theme.hpContent }
  }
}
Boussadjra Brahim
2020-11-06

我刚刚将 this.theme 更改为下面的 this.hpTheme。希望这对您有用。

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
    }
   }
  }
Amaarockz
2020-11-06