Vue: Как очистить фильтр после его применения?

#javascript #vue.js

#javascript #vue.js

Вопрос:

в моем коде Vue js ниже я создал фильтр, поэтому, когда я нажимаю на категорию, он фильтрует, чтобы показывать только связанные, и он работает нормально, но я хотел добавить кнопку, которая очищает фильтр после нажатия с помощью функции ClearFiler() (сброс для отображения всех вопросов без фильтра), но это не работаетесть ли способ это сделать?

и заранее спасибо

 <template>

<div class="container" width=800px>

  <b-row>
  <b-col cols="8">
  <h1> Recently Asked </h1>


     <ul class="container-question" v-for="(question1,index) in questions" :key="index"  
  >
    
   <li >
     {{question1.question}}

 

  <b-row>
   <div class="category" v-for="(categoryy,index) in category(question1)" v-bind:key="index" @click="selectedAnswer(categoryy)">
 
   {{ categoryy }}
   
    
       </div> 

    
  </b-row>
<b-row>


     
  </b-row>
     </li></ul>

  </b-col>
  <b-col>

   
        <div>
  
</div>
  </b-col>

  </b-row>
<router-view />

 </div>

   
</template>
<script>
export default {

  
    data(){
    return{
      questions: [],
       answered: null,
      index: 0,
     selectedIndex: null,
     
     
    }
  },

 watch: {
    question1: {

      handler() {
        this.selectedIndex = null;
       
      },
    },
  },
methods: {

      selectedAnswer(index) {
      this.selectedIndex = index;
      this.questions=this.questions.filter((question) => question.incorrect_answers.includes(index))
      console.log(index)
   
       

    },
    ClearFilter()
    {
      this.question=this.questions //not working
    }

},


  mounted: function(){
fetch('https://opentdb.com/api.php?amount=10amp;category=9amp;difficulty=mediumamp;type=multiple',{
  method: 'get'
})
.then((response) => {
  return response.json()
})
.then((jsonData) => {
  this.questions = jsonData.results
})
  }

}


    

</script> 

Комментарии:

1. Попробуйте this.questions = [] . Если вы хотите что-то сбросить, всегда держите в голове начальное значение по умолчанию, которое в вашем случае является пустым массивом. Прямо сейчас вы устанавливаете значение как текущее значение, поэтому в основном ничего не происходит.

2. я попробовал этот пустой массив, но он также возвращает пустую страницу, в то время как я хочу, чтобы он показывал все вопросы, как в {{question1 . вопрос }}

3. Mhh .. изучая это, в вашем коде, который у вас есть this.question=this.questions , отсутствует s , вы это видите? Этого questions не должно быть question , поскольку question в вашем компоненте нет реактивных данных.

Ответ №1:

Вам необходимо внести соответствующие изменения в стиль.

 new Vue({
      el: '#app',
     data() {
    return {
      questions: null,
      selCategory: "all"
    };
  },
  computed: {
    filterQuestions() {
      return this.selCategory === "all"
        ? this.questions
        : this.questions.filter((item) => item.category === this.selCategory);
    },
    categories() {
      const allCat = this.questions.map((item) => item.category);
      return allCat.filter((item, pos) => {
        return allCat.indexOf(item) == pos;
      });
    }
  },
  mounted() {
    fetch(
      "https://opentdb.com/api.php?amount=10amp;difficulty=mediumamp;type=multiple"
    )
      .then((res) => res.json())
      .then((resp) => {
        this.questions = resp.results;
      });
  },
      
    }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
 <div id="app">
    <div v-if="questions">
    <h1>Recently Asked</h1>
    Filter by Category:
    <select v-model="selCategory">
      <option value="all">All</option>
      <option v-for="cat in categories" :value="cat">{{ cat }}</option>
    </select>
    <hr />
    <table>
      <th><td>Category</td></th>
     <th><td>Question</td></th>
      <tr v-for="(question, index) in filterQuestions" :key="index">
        <td>{{ question.category }}</td>
        <td>
          <p>{{ question.question }}</p>
        </td>
      </tr>
    </table>
    </div>
    <div v-else>
    Loading...
    </div>
  </div>