简体   繁体   中英

Creating a search box with vue.js

I'm wanting to add functionality for the search box to search the current cards on the page for the movie inputted, but all the other examples and solutions I've found online their solutions don't seem to work for me.

This is the body of the HTML:

<body>
  <div id="app">
    <div class="row pt-3">
      <div class="col">
        <input type="text" class="form-control" v-model="search" placeholder="Search Movies">
      </div>
      <div class="col-md-auto">
        <button type="button" class="btn btn-primary" id="search">&nbsp;&nbsp; Go! &nbsp;&nbsp;</button>
      </div>
    </div>
      <div class="row text-center pt-3">
        <div v-for="movie in movies" class="card" style="width: 18rem;">
          <img :src="movie.Poster" class="card-img-top" alt="img">
          <div class="card-body">
            <h5 class="card-title">{{ movie.Title }}</h5>
            <p class="card-text">{{ movie.Year }}</p>
            <a href="#" class="btn btn-primary">View Movie</a>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

</body>

And this the JS file:

new Vue({
  el: '#app',
  data: {
    movies: [],
    search: '',
  },
  created() {
    var vm = this
    axios.get('https://www.omdbapi.com/?s=Harry+Potter&apikey=a9018efb')
      .then(function(response) {
        vm.movies = response.data.Search
      })
  }
})

Instead of looping over movies , create a computed set of filtered data to loop over. For example, if you were searching the titles:

computed: {
   searchedMovies() {
      return this.movies.filter(movie => {
        return movie.Title.toLowerCase().includes(this.search.toLowerCase());
      })
   }
}

Loop over this:

<div v-for="movie in searchedMovies" :key="movie.Title">
...
</div>

When you haven't searched for anything, this will return all movies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM