<body>
<div id="root">
<input type="text" placeholder="请输入要查询的姓名" v-model="keyWord">
<ul>
<li v-for="(value,index) in filPersons" :key="value.id">
{{value.name}}-{{value.age}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false; //阻止vue在启动时生成生产提示
new Vue({
el: "#root",
data: {
keyWord: "",
persons: [
{ id: "001", name: "马冬梅", age: 16, sex: "女" },
{ id: "002", name: "周冬雨", age: 13, sex: "女" },
{ id: "003", name: "周杰伦", age: 12, sex: "男" },
],
filPersons: []
},
//方式一:用watch实现
watch: { //侦听属性
keyWord: {
immediate: true, //当immediate为true,则在初始化时handler会调用一次
handler(val) {
this.filPersons = this.persons.filter(item => item.name.indexOf(val) !== -1)
}
}
},
// 方式二:用computed实现模糊搜索和排序 更简洁
computed: {
filPersons() {
let arr= this.persons.filter(item => item.name.indexOf(this.keyWord) !== -1)
if(this.sortType){ //只有sortType为1或为2时,才为true
arr.sort((a,b)=>this.sortType===1? b.age-a.age : a.age-b.age)
}
return arr
}
}
}
</script>
</body>