vue监听input搜索框是否有输入数据,如果有显示搜索的数据,如果没有则显示全部数据

在Vue中可以使用计算属性(computed)来实现监听搜索框输入数据的功能。
假设有一个data数据为:

data() {  
	return {    
		searchData: '',  
	    items: [   
	       { name: 'item1', category: 'category1' },   
	       { name: 'item2', category: 'category2' },      
	       { name: 'item3', category: 'category1' }, 
	          ] 
 }}

则计算属性可以如下实现:

  computed: {
            filteredItems() {
                if (this.searchData) {
                    return this.items.filter(item => {
                        return item.name.toLowerCase().includes(this.searchData.toLowerCase())
                    })
                } else {
                    return this.items
                }
            }
        }

这里的计算属性filteredItems会根据搜索框的输入数据来过滤数据。如果搜索框有输入数据,则使用Array的filter()方法过滤出符合条件的数据;如果没有输入数据,则返回全部数据。在html中使用
v-for指令渲染数据即可:

<ul>  
<li v-for="item in filteredItems" 
:key="item.name">{{ item.name }} - {{ item.category }}</li>
</ul>

这样就可以实现搜索框输入数据时显示搜索的数据,没有输入数据则显示全部数据的功能

你可能感兴趣的:(vue,vue.js)