html - v-for 用于动态图像网格的 vuejs 中的逻辑
问题描述
所以我一直在草拟算法,看看它是如何工作的。一直在键盘上敲我的头,因为坦率地说,似乎没有任何效果。基本上,硬编码的 HTML 如下所示:
<div class="row">
<div class="column">
<a href="products.html#drinks"><div id="drinks">
<h2>Drinks</h2>
</div></a>
</div>
<div class="column">
<a href="products.html#preppedfood"><div id="preppedfood">
<h2>Prepped Food</h2>
</div></a>
</div>
<div class="column">
<a href="products.html#coffee"><div id="coffee">
<h2>Coffee Machines</h2>
</div></a>
</div>
<div class="column">
<a href="products.html#snacks"><div id="snacks">
<h2>Snacks</h2>
</div></a>
</div>
</div>
<div class="row">
<div class="column">
<a href="products.html#nuts"><div id="nuts">
<h2>Nuts of All Kinds</h2>
</div></a>
</div>...till the last div class="row" and it's column divs
所以 HTML 工作正常,这里有一个截图: 这就是我想要的样子!
但是使用 VueJS 以便我可以“干燥”我的标记,我在 Prods.vue 组件中使用了这样的 v-for 指令。这是模板标记:
<div class="row" v-for="(data, index) in images" v-bind:key="data" v-if="data.ImageId%4 == 0">
<h1>{{index}}</h1>
<div
class="column"
v-for="data in images"
v-bind:key="data"
v-if="computedIndex(index) *4 >= index && index < (computedIndex(index)+1) / 4"
v-lazy-container="{ selector: 'data' }"
>
<a :href="'products/#'+data.Name">
<h4>{{data.H2}}</h4>
<img :src="'../../../static/products/'+data.Name+'.png'" :alt="data.Name+'.png'" />
</a>
</div>
</div>
和脚本:
<script>
import Prods from '../../../other/jsons/products.json'
import VueLazyload from 'vue-lazyload'
export default {
data() {
return {images: Prods}
},
methods: {
computedIndex(index) {
return Math.trunc(index/4)
}
}
}
//v-for in row
//v-for in column
</script>
这就是显示的内容: 在此处输入图像描述
解决方案
而不是玩弄索引,对我来说计算数组的形状以适应你的 DOM 似乎更简单:
computed:
imageRows () {
return this.images.reduce((acc, n, i) => {
i % 4 ? acc[acc.length - 1].push(n) : acc.push([n])
return acc
}, [])
}
要使用这样的东西:
<table>
<tr v-for="(imageRow, i) in imageRows" :key="i">
<td v-for="image in imageRow" :key="image">
<foo/>
</td>
</tr>
</table>
(您的数据对我来说似乎是表格,所以我将此示例显示为,但如果您愿意,当然<table>
可以将其替换为's。)<div>
推荐阅读
- digital-signature - 通过 javacard apdu 发送一个字节 []
- json - lua json解析变量
- android - 取消文件上传(改造)从协程kotlin android开始
- java - 当我向 OM2M 发送 CoAP 消息时发生 nullpointerException
- cefsharp - 将上下文参数传递给 ResourceHandler 的最佳方法是什么
- matlab - 优化定积分
- android - Android Advance Webview 库 - 加载时网页冻结
- javascript - 在 console.log 之后 react-redux 存储中的状态变量未定义?
- c# - 成功发送电子邮件时的C# Outlook删除事件?
- php - 我想随机排序