this的指向问题,具体问题在下面的代码注释里
下面是所有的代码了,需要引入一个vue.js
<div id="list">
<h2>人员列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyWord" /><br /><br />
<li v-for="(objP) in filPersons">{{objP.id}}--{{objP.uname}}--{{objP.age}}</li>
</div>
```javascript
Vue.config.productionTip = false;
const vm = new Vue({//----------------vm在这里-----------------------
el: '#list',
data: {
persons: [
{ id: '001', uname: '李常超', age: 18 },
{ id: '002', uname: '李大哥', age: 28 },
{ id: '003', uname: 'LCC', age: 38 },
{ id: '004', uname: 'Lcc', age: 48 },
],
keyWord: '',
},
computed: {
filPersons() {
//问题在这里,下面的箭头函数我把它换成普通函数就不行,我想应该是this.keyWord的指向问题错了
//打印this.keyWord的this,发现如果是箭头函数的话指向的是vm,就没问题
return this.persons.filter((objP) => {
return objP.uname.indexOf(this.keyWord) !== -1;
});
//但如果是普通函数的话,打印this.keyWord的this,指向的是window
//所以我的问题是,怎么看出来这两个this的指向的啊?
//如果说箭头函数没有自己的this,往外找的话,不是可以找到filPersons这个方法吗?怎么又往上找到vm了呢?
/* return this.persons.filter(function (objP) {
objP.uname.indexOf(this.keyWord) !== -1;
}); */
},
},
});