今天写代码遇到了一个情况,请求的数据通过v-for列表渲染,当鼠标对其中一个div标签鼠标进入的时候才会对这个数据进行筛选,触发filter这时filter中就用到了data中的数据,但是当使用this的时候会出现错误,this undefind,试了好几遍还是不行百度了一下发现filter中的this是全局的不是指向的vue实例,那么也就不能使用this.xxx
- 解决的方法
- 首先定义一个全局的变量
<script>
let that
export default {
}
</script>
- 然后在vue创建前的生命周期钩子函数中将that指向this
beforeCreate () {
that = this
}
- 然后就可以在filter中通过that访问vue实例了
filters :{
filterName(index,value) {//这里的index是v-for的index,就是得到当前是哪一个div
if(value.length > 8 ){
if(index === that.current) {
return value.slice(0,8) + '···'
}else {
return value
}
} else {
return value
}
}
}
希望对小伙伴们有用