Search code examples
vue.jsvuexnuxt.js

How to filter array of data with by category?


Here is my vue page on Nuxt js:

<template> 
  <div>
   <select
    id="category"
    name="category"
    v-model="selected">
     <option value="0">categories</option>
     <option value="1">1</option>
     <option value="2">2</option>
   </select>
   <services-list :list="services.list" /> 
 </div>
<template>

export default {
  components: {
    ServicesList
  },
  data() {
    return {
      services: {
        list: [
          {
            name: 'NAME1',
            title: 'TITLE1',
            category: '1'
          },
          {
            name: 'NAME2',
            title: 'TITLE2',
            category: '2'
          },
         }
        }
       }

I need to filter rendered data based on a selected category from <select>. I tried changing the state on change of <select> but it works only first time. because the data in state would change and running it the second time will not give the correct result.


Solution

  • To get the filtered list from selected, use a computed

    computed{
      filtered(){
        if (this.selected === null) return this.services.list
        return this.services.list.filter(s => s.category === this.selected)
      }
    }
    

    Then you can use filtered in your template