使用高阶函数
filter : 从一个数组中筛选出限定条件的新的数组
form: [ { acount: 10, name: "张一" }, { acount: 2, name: "张二" }, { acount: 23, name: "张三" }, { acount: 42, name: "张四" }, { acount: 1, name: "张五" }, { acount: 3, name: "张六" }, { acount: 5, name: "张七" } ] methods: { onSum() { let acount = this.form.filter(n => { return n.acount < 10;
// 输出 : acount :[{acount: 2,name: "张二"},{acount:1, name: "张五"},{acount:3, name: "张六"},{acount:5, name: "张七"}]
});
},
map:从一个数组中做运算得到另一个数组,或给原数组添加一个属性
let map = this.form.map(item => { return item.acount * 3; }); // 输出 :map: [30, 6, 69, 126, 3, 9, 15]
this.form.map(item => { return item.isCheck = false; });
// 输出 :
form: [
{
acount: 10,
name: "张一",
isCheck: false
},
{
acount: 2,
name: "张二",
isCheck: false
},
{
acount: 23,
name: "张三",
isCheck: false
},
{
acount: 42,
name: "张四",
isCheck: false
},
{
acount: 1,
name: "张五",
isCheck: false
},
{
acount: 3,
name: "张六",
isCheck: false
},
{
acount: 5,
name: "张七",
isCheck: false
}
]
做项目的时候会遇到一个问题,一个后台接口得到的数组,当里边的name = ' ' 或者null 时将不做任何操作,所以需要筛选出来新的数组, 直接用 || 判断时,|| 会存在短路问题,所以用三木判断
form: [ { acount: 10, name: "张一", isCheck: false }, { acount: 2, name: "", isCheck: false }, { acount: 23, name: null, isCheck: false }, { acount: 42, name: "张四", isCheck: false }, { acount: 1, name: "张五", isCheck: false }, { acount: 3, name: null, isCheck: false }, { acount: 5, name: "张七", isCheck: false } ]
let nameData = this.form.filter(n => {
return n.name != null ? (n.name != "" ? true : false) : false;
});
// 输出:
nameData: [
{
acount: 10,
name: "张一",
isCheck: false
},
{
acount: 42,
name: "张四",
isCheck: false
},
{
acount: 1,
name: "张五",
isCheck: false
},
{
acount: 5,
name: "张七",
isCheck: false
}
]
项目中有个需求是 在v-for的多层循环之后,要监听某个input里边的值,这时用watch在网上没有搜索到答案,于是用oninput这个属性,直接是 :oninput,只要input框的值改变都可以实时监听到,十分噻
<ul> <li v-for="(item,index) in form" :key="index" style="margin:10px"> <input type="text" :oninput="seach(item.acount)" v-model="item.acount" /> </li> </ul>
seach(val) {
console.log(val);
},