效果就是可以筛选符合条件的数据
目录
下面给出效果图:
(1)没有输入时的效果
(2)输入 张 的效果
(3)删除 张
变回原来的样子
(4)输入没有的 刘
(5)源代码
<!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 src="../vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="root">
<h2>{{T}}</h2>
<br />
<input type="text" placeholder="请输入名字" v-model="keyWord" />
<ul>
<li v-for="(p,index) in filPersons" :key="index">
{{p.name}}-{{p.age}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false; //阻止 vue在启动时生成生产提示。
new Vue({
el: "#root",
data: {
T: "列表过滤",
keyWord: "",//无论哪个persons的个体都有 ""
persons: [
{ id: "001", name: "张三", age: "18" },
{ id: "002", name: "李四", age: "19" },
{ id: "003", name: "王五", age: "20" },
],
filPersons: [],//过滤后的新数组,由watch得到实时数据
},
watch: {
keyWord: {
immediate: true,//开始时就然其执行handler
handler(val) {
this.filPersons = this.persons.filter((p) => {
return p.name.indexOf(val) !== -1;//不存在的数据返回-1
});
},
},
},
});
</script>
</body>
</html>
用计算属性写
<!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 src="../vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="root">
<h2>{{T}}</h2>
<br />
<input type="text" placeholder="请输入名字" v-model="keyWord" />
<ul>
<li v-for="(p,index) in filPersons" :key="index">
{{p.name}}-{{p.age}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false; //阻止 vue在启动时生成生产提示。
new Vue({
el: "#root",
data: {
T: "列表过滤",
keyWord: "", //无论哪个persons的个体都有 ""
persons: [
{ id: "001", name: "张三", age: "18" },
{ id: "002", name: "李四", age: "19" },
{ id: "003", name: "王五", age: "20" },
],
},
computed: {
filPersons() {
return this.persons.filter((p) => {
return p.name.indexOf(this.keyWord) !== -1; //不存在的数据返回-1
});
},
},
});
</script>
</body>
</html>