IT이야기

Vuejs 검색 필터

cyworld 2022. 5. 27. 21:23
반응형

Vuejs 검색 필터

아래 코드로 받은 아이템 목록을 표시하는 테이블이 있습니다.

interface getResources {
    title: string;
    category: string;
    uri: string;
    icon: string;
}
@Component
export default class uservalues extends Vue {

    resources: getResources[] = [];

    created() {
        fetch('api/Resources/GetResources')
            .then(response => response.json() as Promise<getResources[]>)
            .then(data => {
                this.resources = data;
            });
        }
    }
}

그리고 이게 내 테이블이야

 <div class="panel panel-default">
     <div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
         <div class="row">
             <div class="search-wrapper panel-heading col-sm-12">
                 <input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
             </div>                        
         </div>
         <div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
             <table v-if="resources.length" class="table">
                 <thead>
                     <tr>
                         <th>Resource</th>
                     </tr>
                 </thead>
                 <tbody>
                     <tr v-for="item in resources">
                         <td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
                     </tr>
                 </tbody>
             </table>
         </div>
     </div>
</div>

사용자를 위해 결과를 필터링하는 검색 표시줄을 구현하려고 하는데 잘 모르겠어요!

좋은 의견이라도 있나?

를 사용할 수 있습니다.includes()의 기능array문장이나 구절의 위치를 검색합니다.

new Vue({
  el: '#app',
  data() {
    return {
        searchQuery: null,
        resources:[
            {title:"ABE Attendance",uri:"aaaa.com",category:"a",icon:null},
            {title:"Accounting Services",uri:"aaaa.com",category:"a",icon:null},
            {title:"Administration",uri:"aaaa.com",category:"a",icon:null},
            {title:"Advanced Student Lookup",uri:"bbbb.com",category:"b",icon:null},
            {title:"Art & Sciences",uri:"bbbb.com",category:"b",icon:null},
            {title:"Auxiliares Services",uri:"bbbb.com",category:"b",icon:null},
            {title:"Basic Skills",uri:"cccc.com",category:"c",icon:null},
            {title:"Board of Trustees",uri:"dddd.com",category:"d",icon:null}
        ]
    };
  },
  computed: {
    resultQuery(){
      if(this.searchQuery){
      return this.resources.filter((item)=>{
        return this.searchQuery.toLowerCase().split(' ').every(v => item.title.toLowerCase().includes(v))
      })
      }else{
        return this.resources;
      }
    }
  }
 

})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >

</head>
<body>
<div id="app">
   <div class="panel panel-default">
   <div class="panel-heading">
         <strong> All Resources</strong></div>
            <div class="row">
                 <div class="search-wrapper panel-heading col-sm-12">
                     <input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
                </div>                        
            </div>
        <div class="table-responsive">
            <table v-if="resources.length" class="table">
                <thead>
                    <tr>
                         <th>Resource</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="item in resultQuery">
                        <td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
                    </tr>
                </tbody>
            </table>
        </div>
   </div>
   </div>

</body>
</html>

답변에 기반하여 → 어레이의 Vue.js 검색 키워드

사용할 수 있습니다.computed이 사건의 소유물이니까, 제가 만든 건filteredResources에 사용될 것입니다.v-for루프, 난 더미 데이터를 사용했지만, 넌 그걸 가지고 있을 수 있어resources비어 있다고 선언하고 약속 함수를 호출하여 기입합니다.created가 단일 파일 컴포넌트 또는 CDN을 통해 Vue를 사용하는 다음 코드를 선호할 경우 이 코드를 확인하십시오.

new Vue({
  el: '#app',
  data() {
    return {
      searchQuery:'',
    resources:[
    {title:"aaa",uri:"aaaa.com",category:"a",icon:null},
     {title:"add",uri:"aaaa.com",category:"a",icon:null},
      {title:"aff",uri:"aaaa.com",category:"a",icon:null},
    {title:"bbb",uri:"bbbb.com",category:"b",icon:null},
    {title:"bdd",uri:"bbbb.com",category:"b",icon:null},
    {title:"bsb",uri:"bbbb.com",category:"b",icon:null},
    {title:"ccc",uri:"cccc.com",category:"c",icon:null},
    {title:"ddd",uri:"dddd.com",category:"d",icon:null}
    ]
    };
  },
  computed: {
    filteredResources (){
      if(this.searchQuery){
      return this.resources.filter((item)=>{
        return item.title.startsWith(this.searchQuery);
      })
      }else{
        return this.resources;
      }
    }
  }
 

})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >

</head>
<body>
<div id="app">

   <div class="panel panel-default">
                <div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
                <div class="row">
                    <div class="search-wrapper panel-heading col-sm-12">
                        <input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
                    </div>                        
                </div>
                <div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
                    <table v-if="resources.length" class="table">
                        <thead>
                            <tr>
                                <th>Resource</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in filteredResources">
                                <td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
</div>

</body>
</html>

다음은 간단한 검색의 Vue 3 버전입니다.

const { createApp, ref } = Vue

const App = {
  setup() {
    let searchText = ref('')
    const list = [
      'orange',
      'red',
      'blue',
      'black',
      'white'
    ]
    
    function filteredList() {
      return list.filter(data => data.toLowerCase().includes(searchText.value.toLowerCase()))
    }
    
    return {searchText, filteredList}
  }
}

Vue.createApp(App).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <input type="text" v-model="searchText">
  <ul>
    <li v-for="data in filteredList()" :key="data">
      {{ data }}
    </li>
  </ul>
</div>

이 내비게이션 바의 컴포넌트

<template>
<nav class="navbar navbar-expand-lg navbar-light bg-info display-6">
    <div class="container">
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <form class="d-flex">
                <input v-model="search" class="form-control me-2"  id="inputGroup-sizing-lg" placeholder="Search...">
            </form>
        </div>
    </div>
</nav>
</template>

<script>
import {mapActions} from "vuex"

export default{
    data(){
        return{
            search: ""
        }
    },
    watch:{
        search(newsearch) {
            this.filteredProducts(newsearch)
        }
    },
    methods:{
        ...mapActions([
            "filteredProducts"
        ])
    }
}
</script>

이 가게JS

const store = createStore({
    state: {
        productsList: products,
        cartList: [],
        filtered: []
    },
    mutations:{
        filteredProducts(state, item) {
            if(item){
                state.filtered = products.filter((product) => product.Title.toUpperCase().includes(item.toUpperCase()))
                console.log(state.filtered);
            }
            if(state.filtered){
                console.log("state.filtered.lenght", state.filtered.lenght);
                state.productsList = [...state.filtered]
            }
        }
    },
    actions:{
        filteredProducts (context, item){
            context.commit('filteredProducts', item)
        }
    }
});

쉬운 방법을 찾았어요... "@input 함수"를 사용합니다.나한텐 일인데!

new Vue({
  el: '#app',
  data() {
    return {
      searchQuery:'',
      resources:[
        {title:"aaa",uri:"aaaa.com",category:"a",icon:null},
        {title:"add",uri:"aaaa.com",category:"a",icon:null},
        {title:"aff",uri:"aaaa.com",category:"a",icon:null},
        {title:"bbb",uri:"bbbb.com",category:"b",icon:null},
        {title:"bdd",uri:"bbbb.com",category:"b",icon:null},
      ]
    };
  },
  methods: {
    
    getTextSearch: function(textSearch) {

        this.filteredResources= this.resources

        this.filteredResources= this.filteredResources.filter(item => {
            return item.uri.toLowerCase().includes(textSearch);
        });

    },

  }
 

})

여기 html:

    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >

</head>
<body>
<div id="app">

   <div class="panel panel-default">
                <div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
                <div class="row">
                    <div class="search-wrapper panel-heading col-sm-12">
                        <input class="form-control" @input="getTextSearch($event)" type="text" placeholder="Search" />
                    </div>                        
                </div>
                <div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
                    <table v-if="resources.length" class="table">
                        <thead>
                            <tr>
                                <th>Resource</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in filteredResources">
                                <td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
</div>

</body>
</html>

언급URL : https://stackoverflow.com/questions/52558770/vuejs-search-filter

반응형