uni-app 在 v-for 里使用对象时 index打印为undefined
uni-app 在 v-for 里使用对象时 index打印为undefined
项目信息 | 详细信息 |
---|---|
产品分类 | uniapp/小程序/微信 |
PC开发环境操作系统 | Windows |
PC开发环境操作系统版本号 | win10 |
HBuilderX类型 | 正式 |
HBuilderX版本号 | 3.1.4 |
第三方开发者工具版本号 | 1.03.2012120 |
基础库版本号 | 2.16 |
项目创建方式 | HBuilderX |
操作步骤:
<template>
<view>
<view v-for="(value, name, index) in object" :key="index">
{{ index }}. {{ name }}: {{ value }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2020-04-10'
}
}
}
}
</script>
预期结果:
0.title: How to do lists in Vue, 1.author: Jane Doe, 2.publishedAt: 2020-04-10
实际结果:
undefined.title: How to do lists in Vue undefined.author: Jane Doe, undefined.publishedAt: 2020-04-10
bug描述:
在 v-for 里使用对象 index打印为undefined
更多关于uni-app 在 v-for 里使用对象时 index打印为undefined的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在非H5平台 循环对象时不支持第三个参数,如 v-for="(value, name, index) in object" 中,index 参数是不支持的。
更多关于uni-app 在 v-for 里使用对象时 index打印为undefined的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在uni-app中使用v-for
遍历对象时,index
参数返回undefined
是已知的兼容性问题。这是因为小程序平台(特别是微信小程序)对Vue语法支持的限制。
解决方案:
- 手动计算索引:
<template>
<view>
<view v-for="(value, name, index) in object" :key="name">
{{ getIndex(object, name) }}. {{ name }}: {{ value }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2020-04-10'
}
}
},
methods: {
getIndex(obj, key) {
return Object.keys(obj).indexOf(key);
}
}
}
</script>
- 转换为数组处理:
<template>
<view>
<view v-for="(item, index) in objectArray" :key="index">
{{ index }}. {{ item.key }}: {{ item.value }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2020-04-10'
}
}
},
computed: {
objectArray() {
return Object.keys(this.object).map(key => ({
key: key,
value: this.object[key]
}));
}
}
}
</script>