[Vuejs]-How can I add button to filter some data?

3👍

If you’re not using Vuex, I would probably use v-model to enable/disable certain keywords you want to filter by and then update your filteredMovies computed function to return the selected movies.

Demo

<template>
<div>
   <form>
      <input type="checkbox" name="drama" v-model="filters.drama"/>
      <label for="drama">Drama</label>
      
      <input type="checkbox" name="comedy" v-model="filters.comedy"/>
      <label for="comedy">Comedy</label>
      
      <input type="checkbox" name="horror" v-model="filters.horror"/>
      <label for="horror">Horror</label>
   </form>

   <div v-for="(movie, index) in filteredMovies" :key="movie.title + index">
      <div>
        {{ movie.title }}
      </div>
   </div>
</div>
</template>

<script>
  export default {
    data: ()=>({
      filters: {
        drama: true,
        comedy: true,
        horror: true,
      },
      movies: [
        { title: 'Movia A', genres: ['drama', 'comedy']},
        { title: 'Movia B', genres: ['horror', 'comedy']},
      ]
    }),
    computed: {
      filteredMovies(){
        return this.movies.filter( movie => {
          // create an array of the selected genres from this.filter
          let selectedGenres = Object.keys(this.filters).filter(item => this.filters[item] === true)
          // if this movie includes any of the selected genres, then keep it
                    return movie.genres.some(item => selectedGenres.includes(item))
        })
      }
    }
  }
</script>

Not sure what your end goal is, but you could do the same with a text input field too.

👤zk_

Leave a comment