Home  >  Q&A  >  body text

Toggle active state of button in v-for loop in Vue 3

<p>I'm creating a filter header in Vue 3 where you can select a category to view, so you can click on a switch to toggle the filter and if you click on another category it will deselect the previous activity Categories, there can only be one or no active categories at a time. </p> <p>I found some examples, like this jsfiddle, which doesn't have a toggle button (click again to deselect) and doesn't use a v-for loop. I'm fairly confident I can convert this into a v-for loop, but I don't know how to easily do the switching and having only one active category at a time. </p> <p>This is my basic code: </p> <pre class="brush:html;toolbar:false;"><button v-for="category in contentCategories" @click="" class="filter-button" > {{ category }} </button> </pre> <pre class="brush:js;toolbar:false;">const contentCategories = ["category 1", "category 2", "category 3"]; let list = contentStore.resources; const activeCategory = ""; const filteredList = list .filter((e) => e.category === activeCategory) .map((e) => { return e; }); </pre> <p>The behavior I think I need is to store the active category in the <code>activeCategory</code> string and apply the active label to the corresponding button and then be able to remove it if the active button is clicked again The <code>activeCategory</code>, or changes the <code>activeCategory</code> if a different button is clicked. </p> <p>I'm sorry if this is a simple solution as I'm very new to Vue. Thanks! </p>
P粉046878197P粉046878197419 days ago437

reply all(1)I'll reply

  • P粉588152636

    P粉5881526362023-08-28 00:54:33

    Using the Combination API

    Simple solution for tracking using extra references

    const selectedCategory = ref("")
    const contentCategories = ref(["category 1", "category 2", "category 3"]);
    
    <button
      v-for="category in contentCategories"
      @click="handleClick(category)"
      :class="selectedCategory === category ? 'active' : 'inactive'"
      :key="category"
    >
      {{ category }}
    </button>
    
    handleClick(category) {
       selectedCategory.value = category
    |

    Track category activity if you want to implement multiple selection capabilities

    const contentCategories = ref([
      {
        name: "Category 1",
        active: false
      },
      ...
    ]);
    
    <button
      v-for="category in contentCategories"
      @click="handleClick(category)"
      :class="category.active ? 'active' : 'inactive'"
      :key="category"
    >
      {{ category }}
    </button>
    
    handleClick(category) {
       找到类别然后设置 active = !active,关闭其他类别
    |

    reply
    0
  • Cancelreply