Vue-17、Vue人员列表过滤(案例)

发布时间:2024年01月12日

1、watch实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表渲染过滤</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root">
    <h2>人员列表</h2>
    <input type="text" :placeholder="message" v-model="keyword">
    <ul>
        <li v-for="p in persons2" :key="p.id">
            {{p.name}}-{{p.age}}-{{p.sex}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    Vue.config.productionTip=false;
    new Vue({
        el:"#root",
        data:{
            message:'请输入名字搜索',
            keyword:'',
            persons:[
                {id:'1',name:'马冬梅',age:18,sex:'女'},
                {id:'2',name:'周冬雨',age:20,sex:'女'},
                {id:'3',name:'周杰伦',age:21,sex:'男'},
                {id:'4',name:'文兆伦',age:22,sex:'男'},
            ],
            persons2:[
            ],
        },
       watch:{
            keyword: {
                immediate:true,
                handler(newvalue){
                    console.log(newvalue);
                    const  arr = this.persons.filter((p)=>{
                        return p.name.includes(newvalue);
                    });
                    this.persons2 = arr;
                }
            }
       }
    })
</script>
</body>
</html>

2、computed实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表渲染过滤computed实现</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root">
    <h2>人员列表</h2>
    <input type="text" :placeholder="message" v-model="keyword">
    <ul>
        <li v-for="p in persons2" :key="p.id">
            {{p.name}}-{{p.age}}-{{p.sex}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    Vue.config.productionTip=false;
    new Vue({
        el:"#root",
        data:{
            message:'请输入名字搜索',
            keyword:'',
            persons:[
                {id:'1',name:'马冬梅',age:18,sex:'女'},
                {id:'2',name:'周冬雨',age:20,sex:'女'},
                {id:'3',name:'周杰伦',age:21,sex:'男'},
                {id:'4',name:'文兆伦',age:22,sex:'男'},
            ],

        },
        computed:{
            persons2(){
              const arr = this.persons.filter((p)=>{
                   return  p.name.includes(this.keyword);
                });
                return arr;
            }
        }
    })
</script>
</body>
</html>

在这里插入图片描述

文章来源:https://blog.csdn.net/ChenJin_2/article/details/135556744
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。