我在学习vue的过程中,有一个动态过滤内容的demo,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
<script src="js/vue-resource.min.js"></script>
<style>
p{
width:100px;
height:100px;
background-color: red;
margin:20px auto;
}
</style>
</head>
<body>
<div id="itany">
<input type="text" v-model="name">
<p v-for="(v,k) in arr2" :key="k" v-show="flag">
{{v}}
</p>
</div>
<script>
var vm = new Vue({
el:'#itany',
data:{
flag:true,
arr:['tom', 'jack','mike','alice','alex','mark'],
name:''
},
computed:{
arr2:function () {
var temp=[];
this.arr.forEach(function (val) {
if(val.includes(this.name)){
temp.push(val);
}
});
return temp;
}
// arr2:function () {
// var temp=[];
// this.arr.forEach(val=> {
// if(val.includes(this.name)){
// console.log(val);
// temp.push(val);
// }
// });
// return temp;
// }
}
})
</script>
</body>
</html>
我使用被注释掉的arr2就可以完成动态筛选,但是没有注释掉的arr2就不可以动态筛选。我想知道ES6的arrow和传统的function定义,在这里的区别是什么?
箭头函数和普通函数最大的区别就是this指针的指向,箭头函数的this绑定外层作用域的this,在这里箭头函数的this指向vue示例,所以正常。而匿名函数的this指向window对象,所以this.name并不是你输入框输入的内容,而是window对象的name属性的值,所以不能正常筛选。你可以通过以下代码验证我的想法。