You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中基于类型条件渲染列表,仅展示指定类型项的技术问询

Solution to Filter Vue List by Specified Type

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:

  1. Fixed Items Structure: Your original items was 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 the v-for loop.

  2. Added selectedType Tracking: We added a selectedType data 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.

  3. Computed Property for Efficient Filtering: Using a filteredItems computed property is the cleanest and most performant way to handle list filtering. It automatically updates whenever selectedType or items changes, ensuring your UI stays in sync without extra manual work.

  4. Simplified Template: We removed the unnecessary v-if wrapper 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:51:04