TypeError:无法设置未定义的属性

时间:2020-11-06 17:00:18

标签: vue.js nuxt.js

需要一些支持。

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

<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 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

我刚刚将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
    }
   }
  }

答案 2 :(得分:2)

@WilliamWang的答案非常适合消除该错误,但是如果您只是将单击的主题作为参数传递给this.theme,则您的代码将更加简洁明了:

@click="showDetails(hpTheme)"

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