我需要通过 props 将数组索引传递给子组件,但我无法更改 data 属性的值,当我单击按钮时我会更改该值,因为这些方法不起作用。当我输出到控制台时,出现错误: Uncaught TypeError: good.indexOf is not a function at Proxy.openCard
其他方法也行不通。
我的代码是模板:
<button @click="openCard()">More!</button>
<!-- other code line... -->
<CardItem class="z-20 bg-white" :good="goods[indexOfGood]"></CardItem>
我的脚本代码:
methods: {
openCard() {
this.isHide = !this.isHide;
for (let i = 0; i < this.goods.length; i++) {
let good = this.goods[i];
this.indexOfGood = good.indexOf();
// console.log(good.indexOf());
}
}
}
我尝试使用其他方法也不起作用(例如:at()、chaining()和其他方法)
根据您的描述,似乎对如何使用 indexOf 以及 openCard 方法中循环背后的意图存在误解。 indexOf 方法用于查找数组中元素的索引,但您尝试在数组 (this.goods) 的元素(good)上使用它,该元素没有 indexOf 方法,因此错误。
如果您的目标是在单击按钮时将特定项目(好)的索引传递给 CardItem 组件,则需要调整您的方法。这是 openCard 方法的修订版本以及有关如何实现目标的建议:
修改openCard方法 假设您想循环遍历货物数组并在每次单击按钮时更新indexOfGood,您可以执行以下操作:
methods: {
openCard() {
this.isHide = !this.isHide;
if (this.goods.length > 0) {
if (this.indexOfGood < this.goods.length - 1) {
this.indexOfGood++;
} else {
this.indexOfGood = 0;
}
}
}
}