v-for中的索引问题及图片的src绑定问题


1. 将v-for中的索引作为点击函数的参数传递到vue对象的函数中。

在表格中循环输出list集合中的内容,list里有多少数据有多少行。注意点击函数:@click="decrease(index)",要想将循环的索引作为函数的参数就直接在括号写index即可,不要写 $ index和{{index}}。
```
<!-- 循环输出list数组中的商品对象 -->
<tr v-for="(item,index) of list" :key="index">
<td class="center"><img :src="item.mysrc" width="60" height="40"/></td>
<td class="center">{{item.myspan}}</td>
<td class="center">
<input type="button" value="-" @click="decrease(index)"/>
{{item.num}}
<input type="button" value="+" @click="increase(index)"/>
</td>
<td class="center">{{item.total}}</td>
<td class="center"><input type="button" value="删除商品" @click="delCommodity(index)" /></td>
</tr>
```

若想在页面中直接显示索引的话就写{{ $index}},例如:

```
<td>{{index}}</td>
```
这样的话就会在页面中显示出索引。若无法显示出索引的话可以试试写成 {{$index}}。


2. v-for中图片的src属性的绑定,还是上面的例子

```
<!-- 循环输出list数组中的商品对象 -->
<tr v-for="(item,index) of list" :key="index">
<td class="center"><img :src="item.mysrc" width="60" height="40"/></td>
<td class="center">{{item.myspan}}</td>
<td class="center">
<input type="button" value="-" @click="decrease(index)"/>
{{item.num}}
<input type="button" value="+" @click="increase(index)"/>
</td>
<td class="center">{{item.total}}</td>
<td class="center"><input type="button" value="删除商品" @click="delCommodity(index)" /></td>
</tr>
```
这里注意:src中的写法,要用v-bind即:绑定,item为循环中的每一项,这里的list存的是一个一个的对象即[{mysrc:"../img/mei.jpg",...},{mysrc:"../img/saber.jpg",...}..],对象中的其他属性省略。

这样item.mysrc就能获得list集合中每一项对应的图片地址。不要写成src="{{item.mysrc}}",这是错误的。

```
<img :src="item.mysrc" width="60" height="40"/></td>
```

若想在页面中直接输出集合中内容,就写成{{item.num}},item为循环中的每一项,num为对象中的属性名,例如

```
<td class="center"> {{item.num}}</td>
```
这样页面中就会显示出num属性对应的属性值。

猜你喜欢

转载自www.cnblogs.com/pixiec/p/10808541.html
今日推荐