Vue.js中如何将数组元素添加到id匹配dealState值的div中
Solution for Vue.js Row and Data Matching
Here's a straightforward implementation that renders your row names and groups the data items under their corresponding rows based on dealState:
<template> <div class="deal-container"> <!-- Iterate over each row definition --> <div v-for="row in arrayForRowNames" :key="row.id" class="deal-row"> <h3 class="row-header">{{ row.name }}</h3> <!-- Container for matching deal items --> <div class="deal-items"> <!-- Loop through filtered items for this row --> <div v-for="item in getDealsForRow(row.id)" :key="item.id" class="deal-item"> <p><strong>Deal Title:</strong> {{ item.title }}</p> <p><strong>Value:</strong> {{ item.value }} {{ item.currency }}</p> <p><strong>Comment:</strong> {{ item.comment }}</p> </div> <!-- Fallback if no deals exist for this row --> <div v-if="getDealsForRow(row.id).length === 0" class="empty-state"> No deals found in this state. </div> </div> </div> </div> </template> <script> export default { data() { return { arrayForRowNames: [ { id: 1, name: "Lead in " }, { id: 2, name: "Contact Made" } ], dataArray: [ { id: 1, title: "bottle sell", value: "100", currency: "default", comment: "cheap deal", dealState: "1" }, { id: 2, title: "[wheel sell][1]", value: "0", currency: "default", comment: "MFD", dealState: "2" } ] }; }, methods: { getDealsForRow(rowId) { // Convert dealState to number to match the row's numeric id return this.dataArray.filter(deal => Number(deal.dealState) === rowId); } } }; </script> <style scoped> .deal-container { max-width: 900px; margin: 2rem auto; padding: 0 1rem; } .deal-row { margin-bottom: 2rem; padding: 1.5rem; border-radius: 8px; border: 1px solid #e0e0e0; } .row-header { margin-top: 0; color: #2d3748; } .deal-item { padding: 1rem; margin: 1rem 0; background-color: #f7fafc; border-radius: 4px; } .empty-state { color: #718096; font-style: italic; padding: 1rem; } </style>
Key Details Explained:
- Row Rendering: We use
v-forto loop througharrayForRowNames, creating a section for each row with its name as a header. - Data Filtering: The
getDealsForRowmethod filtersdataArrayto find items wheredealState(converted to a number) matches the row'sid. This handles the type mismatch between the stringdealStateand numericid. - Fallback State: If a row has no matching deals, we show a friendly empty message using
v-if. - Reactivity & Efficiency: Adding
:keyattributes to both loops ensures Vue can efficiently update the DOM when data changes. - Styling: The scoped CSS adds clean, modern styling to make the layout easy to read without affecting other parts of your app.
If you need to handle markdown links in the title field (like [wheel sell][1]), you'd need to add a markdown parser library (like marked), but that's an extra step. For now, this code renders the title as plain text as provided.
内容的提问来源于stack exchange,提问作者user3699711
相关产品推荐
相关产品推荐

