11-2.Vue2.x基本列表—列表过滤 filter--computed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>基本列表</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
想要对数据进行加工后再展示且不想破坏原数据,最好用computed计算属性
-->
<!-- 准备一个容器 -->
<div id="root">
<h2>人员列表</h2>
<input v-model="keyWord" type="text" placeholder="请输入姓名" />
<ul>
<!-- <li v-for="(p,index) in persons">
{{p.name}}---{{p.sex}}---{{p.age}}岁
</li> -->
<li v-for="(p,index) in fmtPersons">
{{p.name}}---{{p.sex}}---{{p.age}}岁
</li>
</ul>
</div>
<script>
new Vue({
el: "#root",
data: {
keyWord: "",
persons: [
{ id: "001", name: "马冬梅", age: 20, sex: "男" },
{ id: "002", name: "周冬雨", age: 29, sex: "女" },
{ id: "003", name: "周杰伦", age: 32, sex: "男" },
{ id: "004", name: "温兆伦", age: 50, sex: "女" },
],
},
// 使用computed优势,列表过滤不影响
// 计算属性(keyWord变时,调用fmtPersons)
computed: {
fmtPersons() {
const { persons, keyWord } = this;
return persons.filter((p) => p.name.indexOf(keyWord) !== -1);
},
},
methods: {
demo() {
console.log(1);
},
},
// 在watch中修改原数据,会造成原数据丢失
// watch: {
// keyWord(value) {
// console.log(value);
// const arr = this.persons.filter(
// (p) => p.name.indexOf(value) !== -1
// );
// this.persons = arr;
// console.log(arr);
// },
// },
});
</script>
</body>
</html>