Home » vue » Vue onclick filter

Vue onclick filter

Posted by: admin November 26, 2021 Leave a comment

Questions:

Dear Stack Overflowuser,

Under this fiddle is a code, with which a onclick filter in Vue JS was tried to built. However, the approach does not function yet.

The JS is in lines 118 – 120. Code obtained from fiddle.

Code is only in the jsfiddle, since posting the code is due to Stack Overflow functions not possible.
Thanks in advance for any help that makes the onclick filter work in the jsfiddle.

Desired result is a click function showing only the products with a merchant, which is the name of the button.

Yours sincerely

Esko Nielson

Answers:

There are several issues in your code, that prevent you from getting the wanted result:

  • You mix Vue methods with regular window methods. The filterSelection method is defined twice – first as a part of Vue methods definition, and then again afterwards. What you will notice is that just the second one gets called.

  • You use regular js functions to modify the DOM. That is very contrary to what VueJS is doing. Instead of adding or removing classes with custom made methods, you could use the proper way Vue does that: class="{ show: propertyFromVue }". This would toggle the show class on and off, based on the propertyFromVue boolean value.

  • The list of toppings is defined once and just displayed. You need a second variable that holds only the "filtered" items. This could be done through a computed property:

      computed: {
        filteredToppings: () => this.toopings
          .filter((topping) => !!topping.vendors
            .find((vendor) => vendor.merchang === this.filterSelectionText)
          );
      }
    

    This would only work if your VueJS filterSelection method is called and filterSelectionText property is updated.

    Then you can use this filteredToppings to display the list of filtered items 🙂 Good luck!