列表过滤
监视属性,实现列表过滤
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本列表</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<!-- 遍历数组 -->
<h2>人员列表</h2>
<input type="text" placeholder="请输入要查询的名字" v-model="keyWord">
<ul>
<li v-for="(p,index) in persons2" :key="index">
姓名:{{p.name}}    年龄:{{p.age}}    性别:{{p.sex}}
</li>
</ul>
</div>
<script type="text/javascript">
// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false
new Vue({
el:"#root",
data(){
return{
// 收集用户的输入
keyWord:"",
persons:[
{id:"001",name:"马冬梅",age:20,sex:"女"},
{id:"002",name:"周冬雨",age:21,sex:"女"},
{id:"003",name:"周杰伦",age:22,sex:"男"},
{id:"004",name:"温兆伦",age:23,sex:"男"}
],
persons2:[]
}
},
watch:{
// 监视 keyWord 属性
keyWord:{
//immediate为true时,初始化时调用一下handler()函数
immediate:true,
handler(newValue,oldValue){
// 数组.filter() 实现数组的过滤,创建一个新数组, 其包含通过所提供函数实现的测试的所有元素
this.persons2 = this.persons.filter((p)=>{
// 当 keyWord 是 p.name 中的内容,返回true,否则返回false
return p.name.indexOf(newValue) !== -1
})
}
}
}
})
</script>
</body>
</html>
