<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>VUE-列表过滤</title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
<div id="app">
<h2>人员列表</h2>
<input type="text" placeholder="请输入姓名" v-model="keyword">
<ul>
<li v-for="(p,index) in newpersons" :key="index">
{{p.name}}--{{p.age}}--{{p.sex}}
</li>
</ul>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
keyword: "",
persons: [{
id: "001",
name: "马冬梅",
age: "19",
sex: "女"
}, {
id: "002",
name: "周冬雨",
age: "20",
sex: "女"
}, {
id: "003",
name: "周杰伦",
age: "21",
sex: "男"
}, {
id: "004",
name: "温兆伦",
age: "22",
sex: "男"
}],
newpersons: []
},
watch: {
//1.标准的完整写法
keyword: {
immediate: true, //加上这句,开始执行一次。return p.name.indexOf(val) !== -1 都符合界面有数据
handler(val) {
// console.log(val) //input 输入的值
// 使用filter过滤掉 不能改变原始数据persons 改用遍历新数据newpersons来渲染
this.newpersons = this.persons.filter((p) => {
// 包含val输入的值val -1是无匹配 不等于就是匹配到了
return p.name.indexOf(val) !== -1
})
}
}
}
});
</script>
</body>
</html>
效果图:
首次进入界面
输入查询过滤效果: