Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

javascript - Vue js:filter on array not working in my code

in my Vue js code i've created a search input with dropdown, the data of drop down are API data array categories i'm trying to create filter on the input search bar so whenever a value typed in input search bar it should show in drop down menu from API, my code here isn't applying the filter (not working).any help?

<template>

  <div class="dropdown">
    <input v-model.trim="inputValue" class="dropdown-input" type="text" placeholder="Find country" />
    <div v-show="inputValue" class="dropdown-list">
      <div   v-for="(category, index) in FilterCategories"
              :key="index" class="dropdown-item"
            {{ category.category_name }}

      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import questionService from "../services/questionService";

export default {
  name: "postComponent",
  components: {},
  
  data() {
    return {
      inputValue: '',
      categories: [],
   
    };
  },
  methods: {
       FilterCategories() { //not working
   
        return  this.categories.filter(categories => {
        return categories.category_name===this.inputValue
        });
     
    },},
    
  mounted: function () {
    questionService.getCategories().then((response) => {
      this.categories = response.data.response;
      
     
    });
  },
};
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

using computed property would be better option

computed: {
       FilterCategories() {
        return  this.inputValue ? this.categories.filter(category => {
          return category.category_name.toLowerCase().includes(this.inputValue.toLowerCase())
        }) : this.categories;  
    }
}

**No changes are required in template


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...