vue.jsfiltervuetify.jsv-btn

How to filter a product list using v-btn in vuetify?


I am currently trying to filter a list of objects by using buttons.

I know that both v-btn and v-card loops are not currently interdependent, but I am unable to figure out how to link both sections to properly show only the correct category when pressing its respective button.

Thanks for the help!

        <v-row class="my-4">
          <v-btn
          v-for="category in categories"
          text
          class="underline"
          route :to="category.route"
          @click="category.function"
          >{{ category.text }}</v-btn>

        </v-row>
        <v-row 
        justify="start">
          <v-card
          v-for="product in products"
          :key="product.name"
          class="ma-3 text-center">
          <v-img
          :src="product.src"
          class="mc mt-2"
          >
          </v-img>
          <v-card-title
          class="bold justify-center">
            <h4>{{ product.name }}</h4>
          </v-card-title>
          </v-card>
        </v-row>

categories: [
                { text: 'All', function: "all()" },
                { text: 'Fruits & Veggies', function: "fruitsVeggies()"  },
                { text: 'Baking', function: "baking"  },
                { text: 'Gadgets', function: "gadgets"  },
                { text: 'Cutting Boards', function: "cuttingBoards"}],  


products: [{...}, {...}, etc]


computed: {
      all() {
        return this.products.filter(product => {
          return product
        })
      },
      fruitsVeggies() {
        return this.products.filter(product => {
          return product.category === 'Fruits & Veggies'
        })
      },
      baking() {
        return this.products.filter(product => {
          return product.category === 'Baking'
        })
      },
      cuttingBoards() {
        return this.products.filter(product => {
          return product.category === 'Cutting Boards'
        })
      }


Solution

  • Vue computed properties return a dynamic value
    When you call baking as a function, it should throw an error in the console; it's not a function, but a property

    Instead, you could define a computed property called filteredProducts that changes filter based on something stored in the data, and loop over that instead

    data() {
      productFilter: "all"
    }
    
    computed: {
      // your computed values
      filteredProducts() {
        if (this.productFilter === "all") {
          return this.all;
        }
        // etc. For all filters
      }
    }
    

    Then in your template:

    <v-row 
      justify="start"
    >
      <v-card
      v-for="product in filteredProducts"