记录问题:使用双v-for时遇到的问题

81 阅读1分钟

原代码:

<view class="tabel-item" v-for="(item, index) in listData" :key="index"> 
    <view class="item-text" v-for="(data, index) in headData" :key="index"> 
        <template v-if="data.prop.indexOf('image') === -1">{{ item[data.prop] || "-" }}</template> 
        <image v-else @click="previewImage(item[data.prop])" class="item-image" :src="'../static/img.png'" mode="scaleToFill" /> 
    </view> 
</view>

出现的问题: previewImage(item[data.prop])无论哪一项传传过去的值都是一样的。

问题出现的原因:后一个v-forindex重置了前面一个index,使得取值时,取错了值。

改正:不要取相同的key,把其中一个index改掉。

代码:

<view class="tabel-item" v-for="(item, index) in listData" :key="index"> 
    <view class="item-text" v-for="(data, i) in headData" :key="i"> 
        <template v-if="data.prop.indexOf('image') === -1">{{ item[data.prop] || "-" }}</template> 
        <image v-else @click="previewImage(item[data.prop])" class="item-image" :src="'../static/img.png'" mode="scaleToFill" /> 
    </view> 
</view>


个人理解: 这里的previewImage(item[data.prop]) === previewImage(item[index][data[index].prop])。当后一个index重置了前面一个indexitem[index]取值的时候,这里的indexheadData"循环出来的index,而不是listData" 。

仅为个人见解,欢迎各位补充