代码是这样的,在data中定义了一个名为AnimatorChoices的属性并设置为false
data() {
return {
AnimatorChoices: false
}
},
在methods中打印
methods: {
upOptions() {
console.log(this.AnimatorChoices) //这里输出false
onscroll = function () {
let height = document.body.scrollTop || document.documentElement.scrollTop;
if (height > 80) {
console.log(this.AnimatorChoices) //这里输出为什么为undefined
this.AnimatorChoices = true;
console.log(this.AnimatorChoices)
}
}
}
},
方法在created声明周期函数中调用
created() {
this.upOptions()
}
为什么会输出undefined
你在upOptions方法里面又建了一个方法onscroll, 此时onscroll的this不是当前vue对象。
简单理解就是method的中的单层方法才可以直接调用data。
解决方法一:使用回调函数
解决方法二:that=this
this应该不是一个对象
this的指向问题
可以使用箭头函数,保持函数内this指向和函数外部this指向一致,都指向vue实例
onscroll = () => {}