疑问
今天写了一个下面的for循环遍历代码,但是一直前端界面展示不出来,后来发现是由于ref的原因
<view v-for="(p,i) in products" :key="p.id" class="product-item" :style="{ top: (i*150)+'px' }" @tap="viewProduct(p)">
<view class="frame-3_155">
<view class="vector-3_156"></view>
<view class="vector-3_157"></view>
</view>
<text class="text-3_158">{{ p.name }}</text>
<text class="text-3_159">{{ p.price }}</text>
<view class="rectangle-3_160"></view>
<text class="text-3_161">{{ p.desc }}</text>
<text class="text-3_162">选规格</text>
</view>
const products = ref([
{ id: 1, name: '商品名称A', price: '¥88', desc: '商品说明A' },
{ id: 2, name: '商品名称B', price: '¥128', desc: '商品说明B' },
{ id: 3, name: '商品名称C', price: '¥56', desc: '商品说明C' },
{ id: 4, name: '商品名称D', price: '¥99', desc: '商品说明D' },
{ id: 5, name: '商品名称E', price: '¥149', desc: '商品说明E' }])
把ref()去掉之后就能正确显示了
搜索资料原因如下:
- 把 ref([...]) 去掉后,模板直接拿到的是一个普通数组, v-for 不需要做响应式解包就能渲染初始值,所以能显示。
- 使用 ref([]) 时,模板需要对 ref 做“解包”才能迭代。
做法
-
显式解包 ref :
- 模板改为: v-for="(p,i) in products.value"
-
用 reactive([]) 管数组:
- 不要整体重赋值,使用变更方法更新:
- products.splice(0, products.length, ...newList) 或 products.push(...newList) 注意事项
- 不要整体重赋值,使用变更方法更新:
-
初始化与更新统一用同一种写法:
- ref :初始化 products.value = [...] ,更新也用 products.value = [...]
- reactive :初始化为 reactive([]) ,更新用 splice/push 等