需要一些支持。
我想通过单击按钮或链接来显示数据
<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”。 怎么解决? 感谢您的支持。
答案 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 }
}
}