Vue中基于类型条件渲染列表,仅展示指定类型项的技术问询
Let's fix the issues in your original code and implement the filtering functionality properly:
Corrected Full Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <!-- Optional: Add buttons to switch between displayed types --> <button @click="selectedType = 'a'">Show Type A</button> <button @click="selectedType = 'b'">Show Type B</button> <div v-for="(item, index) in filteredItems" :key="index"> <p>{{ item.text }}</p> </div> </div> <script> export default { el: '#app', data() { return { selectedType: 'a', // Default to showing items of type 'a' items: [ // Fixed: items should be an array, not an object { type: "a", text: "TEXT A" }, { type: "b", text: "TEXT B" }, { type: "b", text: "TEXT B-1" }, { type: "a", text: "TEXT A-2" } ] } }, computed: { filteredItems() { // Filter items to only those matching the selected type return this.items.filter(item => item.type === this.selectedType); } } } </script>
Key Fixes & Explanations:
Fixed Items Structure: Your original
itemswas declared as an object ({ ... }) but it needs to be an array ([ ... ]) since it's a list of individual items. This was a critical syntax error that would break thev-forloop.Added
selectedTypeTracking: We added aselectedTypedata property to keep track of which type we want to display. You can set its default value to 'a' or 'b' based on your needs.Computed Property for Efficient Filtering: Using a
filteredItemscomputed property is the cleanest and most performant way to handle list filtering. It automatically updates wheneverselectedTypeoritemschanges, ensuring your UI stays in sync without extra manual work.Simplified Template: We removed the unnecessary
v-ifwrapper and instead loop directly through the pre-filtered items. The optional buttons let you switch between types on the fly—you can remove them if you just want to hardcode a single type to display.
If you want to hardcode the filter to always show, say, type 'a' without switching ability, simplify the computed property to:
filteredItems() { return this.items.filter(item => item.type === 'a'); }
And remove the buttons from the template.
内容的提问来源于stack exchange,提问作者Aishwerya

