使用场景
列表展示的数据比较多,我们想要进行模糊搜索,在这么多的数据里面找到我们需要的。
也就是后端一下子把所有的数据都返回,我们前端进行模糊搜索的时候,不会调用后端的接口,直接进行模糊搜索,如何实现
使用watch进行监听的具体代码
页面遍历过滤后的list数据
使用watch进行监听
watch:{
keyword:{
immediate:true,
handler(value){
console.log(value)
this.filstus = this.stus.filter((p)=>{
return p.name.indexOf(value) !== -1
})
}
}
}
使用计算属性进行模糊查询
升序降序
对查询出来的数据进行升序降序,之前我们已经实现了模糊查询,现在就是要对查询出来的数据进行升序降序
直接用计算属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../js/vue.js"></script>
<style> .div1{
width: 100px; height: 50px; background-color: aquamarine; } .div2{
width: 90px; height: 20px; background-color: blueviolet; } .list{
width: 200px; height: 200px; background-color: blueviolet; overflow: auto; } li{
height: 20px; } </style>
</head>
<body>
<div id="root">
<input type="text" placeholder="请输入姓名" v-model="keyword">
<button @click="sortType = 2">升序</button>
<button @click="sortType = 1">降序</button>
<button @click="sortType = 0">原来模式</button>
<ul>
<li v-for="(item,index) in filstus" :key="index">
{
{item.name}}----{
{item.age}}
</li>
</ul>
</div>
<script > Vue.config.productionTip = false new Vue({
el: '#root', // data:function(){
return{
keyword:'', sortType:0,//0 原顺序 1 降序 2 升序 stus:[ {
"name":"马冬梅", "age":17 },{
"name":"周冬雨", "age":18 },{
"name":"周姐", "age":19 } ] } }, computed:{
filstus(){
const arr = this.stus.filter((p)=>{
return p.name.indexOf(this.keyword) !== -1 }) if(this.sortType){
arr.sort((a,b)=>{
return this.sortType == 1 ? b.age - a.age : a.age -b.age }) } return arr } }, methods:{
} , }) </script>
</body>
</html>