请问这种怎么办?uniapp-x 试了 view swiper-item template 都不支持v-for 那么怎么循环取数据啊?
欢迎到专业群( uni-app x技术交流群 ) 咨询,群中有相关专业的管理员和群友。
view、swiper-item、template 组件都支持 v-for。你遇到的问题根源在于 uts 是强类型语言,没有明确声明数据类型的数组会被推断为 utsjsonobject[],这在 v-for 中无法直接通过 . 访问属性。
解决方法是给你的数组数据定义明确的类型。
问题本质
uni-app x 使用 uts 强类型语言。当你在 <script setup> 中写:
const list = ref([
{ id: 1, text: 'a' },
{ id: 2, text: 'b' }
])
本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码
编译器无法推断数组元素的具体结构,会把它当作 utsjsonobject[]。在 v-for 里写 item.text 就会报编译错误 unresolved reference: text,因为 utsjsonobject 类型上没有 text 这个属性。
这不是 v-for 不工作,而是 uts 的强类型约束在起作用。
正确做法:先定义类型,再使用 v-for
方式一:使用 interface 定义类型
<template>
<view>
<view v-for="item in list" :key="item.id">
<text>{{ item.text }}</text>
</view>
</view>
</template>
<script setup lang="uts">
interface listitem {
id : number
text : string
}
const list = ref<listitem[]>([
{ id: 1, text: 'a' },
{ id: 2, text: 'b' },
{ id: 3, text: 'c' }
])
</script>
本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码
方式二:使用 type 别名
type listitem = {
id : number
text : string
}
const list = ref<listitem[]>([
{ id: 1, text: 'a' },
{ id: 2, text: 'b' }
])
本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码
方式三:使用 utsjsonobject 配合方括号访问
如果确实不想定义类型(不推荐),可以用方括号语法访问属性:
<template>
<view v-for="item in list" :key="item['id']">
<text>{{ item['text'] }}</text>
</view>
</template>
<script setup lang="uts">
const list = ref([
{ id: 1, text: 'a' },
{ id: 2, text: 'b' }
])
</script>
本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码
这种方式在模板中写 item['text'] 而不是 item.text,可以绕过类型检查。
swiper-item 中使用 v-for 的完整示例
swiper 组件完全支持 v-for,下面是官方的垂直视频滑动示例,它就在 swiper-item 上用了 v-for:
<template>
<view class="page">
<swiper class="swiper" :current="current" :vertical="true" @change="onswiperchange">
<swiper-item class="swiper-item" v-for="(item, i) in visiblelist" :key="i">
<video class="video-box" :src="item.src"></video>
<text>{{ item.content }}</text>
</swiper-item>
</swiper>
</view>
</template>
<script setup lang="uts">
type videoitem = {
src : string
poster_src : string
content : string
}
const visiblelist = ref<videoitem[]>([
{
src: 'https://example.com/video1.mp4',
poster_src: '',
content: '第一个视频'
},
{
src: 'https://example.com/video2.mp4',
poster_src: '',
content: '第二个视频'
}
])
const current = ref(0)
function onswiperchange(e : uniswiperchangeevent) {
current.value = e.detail.current
}
</script>
本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码
list-view 中 v-for 的注意事项
如果使用 list-view 组件,也要遵循同样的原则:
<template>
<list-view style="flex: 1">
<list-item v-for="item in list" :key="item.id">
<text>{{ item.content }}</text>
</list-item>
</list-view>
</template>
<script setup lang="uts">
type listitem = {
id : number
content : string
}
const list = ref<listitem[]>([
{ id: 1, content: "测试1" },
{ id: 2, content: "测试2" }
])
</script>
本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码
验证方法
. 访问属性 uni-app x 的 v-for 在 view、swiper-item、template 等组件上都完全可用。核心就是记住 uts 的强类型规则:先声明类型,再使用数据。