html - Vue.js- 在表格上渲染价格比较
问题描述
我有一个用例,我正在努力拼凑。我想显示来自不同商店的商品价格,如下图所示。
我的问题是我得到下表;
我桌子上的输出不正确。Zimgold 的价格仅在 Spar 中可用。但在这里它显示在所有其他商店下。Raha 也是如此。它的价格应该低于 OK。如果他们没有该产品,我希望其他商店有一个破折号或空行。
这是我的 vue.js 代码:
<modal ref="comparisonTable" no-close-on-backdrop no-close-on-esc hide-cancel width="600px" title="GENERATE BILL" :hide-ok="true" hide-footer centered>
<Spinner v-show="productsLoader" :message="productsLoaderMessage" size="medium"></Spinner>
<table class="table table-striped " v-show="productsTable" width="100%">
<!--Table head-->
<thead>
<tr class="table-info">
<th>Product Brands</th>
<th v-for="company in selectedCompaniesDetails" :key="company.id">
{{company.name}}
</th>
<th>Pick</th>
</tr>
</thead>
<!--Table head-->
<!--Table body-->
<tbody>
<tr v-for="product in products" :key="product.id">
<th scope="row">
{{product.name}}
</th>
<td v-for ="totalCompanies in totalSelectedCompanies" :key="totalCompanies">
<span>
{{product.price}}
</span>
</td>
<td>
<input type="checkbox" style="margin:10px;" v-model="selectedProducts" :value="product"/>
</td>
</tr>
<tr>
<th scope="row">
</th>
<td v-for ="totalCompanies in totalSelectedCompanies" :key="totalCompanies">
</td>
<th>
<button @click="generateFinalBill($event)">
GENERATE BILL
</button>
</th>
</tr>
</tbody>
</table>
</modal>
解决方案
在您的示例中,您有两个嵌套的 for 循环,外部一个循环通过products
,内部一个循环通过totalSelectedCompanies
. 问题是您的product.price
变量仅随着外部循环的每次迭代而变化。为了为每次迭代显示不同的价格,您需要让值受到内部循环的影响。
您执行此操作的方式取决于价格的存储或计算方式,但一种方法是将每个卖家的价格存储在产品对象中并循环:
<tr v-for="product in products" :key="product.id">
<th scope="row">
{{product.name}}
</th>
<td v-for ="seller in product.sellers">
<span>
{{seller.price}}
</span>
</td>
<td>
<input type="checkbox" style="margin:10px;" v-model="selectedProducts" :value="product"/>
</td>
</tr>
这样做的一个问题是,无论他们是否实际销售,您都必须让每个卖家都在 product.sellers 中。相反,我会创建一个从给定公司返回产品价格的方法,然后您可以执行以下操作:
<tr v-for="product in products" :key="product.id">
<th scope="row">
{{product.name}}
</th>
<td v-for ="company in selectedCompanies">
<span>
{{calculateCompanyPrice(product, company)}}
</span>
</td>
<td>
<input type="checkbox" style="margin:10px;" v-model="selectedProducts" :value="product"/>
</td>
</tr>
calculateCompanyPrice()
然后将包含从给定产品和公司返回所需价格的所有逻辑,包括在公司不销售给定产品时显示破折号。
编辑:值得注意的是,从技术上讲,您可以在您{{ }}
的 s 之间放置任何有效的 javascript,因此我确信还有许多其他方法可以在内循环中输出正确的价格。
推荐阅读
- python - Django-Storages ('`data` 必须是字节,已接收',
) 保存模型字段时 - python-3.x - 如何跟踪用户输入的分数?
- cuda - 其他块的线程是否可以访问内核中使用 malloc 分配的内存?
- python - 使用类型作为函数参数的 Pythonic 方式
- javascript - 从同一组件链接到组件不起作用
- html - 在我的选项卡式内容框中将嵌入的 Youtube 视频居中
- javascript - 如何重新加载 nuxt .js 的自定义布局?
- python - 在不改变维度的情况下连接两个向量的最佳方法是什么?总和,平均值,中位数..等
- haskell - 无法使用 cabal 安装 Random 模块?(哈斯克尔)
- firebase - Firebase 存储/gcloud 存储不适用于 Unity 资源包