vue新人求助下,为什么用箭头函数无法获取this.isPhoneFooter的值

我的switchPhone函数用箭头函数的方式写无法获取到this.isPhoneFooter的值但是换成
switchPhone(){}就可以正确获取到,这是什么原因?

代码如下

export default{
        data(){
            return {
                isPhoneFooter: true,
                active: false,
                items01: [
                    {select:'目标检测'},
                    {select:'图像分类'},
                    {select:'人体识别'},
                    {select:'人脸识别'},
                    {select:'文字处理'},
                    {select:'音频处理'}
                ],
                items02: [
                    {select:'精彩预览'},
                    {select:'智能集锦'},
                    {select:'物料/海报生成'},
                    {select:'3D原生植入'},
                    {select:'动态浮层植入'}
                ],
                items03: [
                    {select:'推荐算法'},
                    {select:'以图搜影'},
                    {select:'聚类分析'}
                ]
            }
        },
        methods: {
            switchPc() {
                //console.log('切换电脑版');
                //let w= document.documentElement.clientWidth || document.body.clientWidth;
                //let h= document.documentElement.clientHeight || document.body.clientHeight;
                //document.getElementsByTagName('body')[0].style.zoom= '0.1';
                this.isPhoneFooter = false;
            },
            switchPhone:()=>{
                //console.log('切换手机版');
                document.getElementsByClassName('phone_home_middle')[0].style.width = '150px';
                this.isPhoneFooter = true;
            }
        }
    }
阅读 1.8k
3 个回答

原文链接

注意,不应该使用箭头函数来定义 method 函数 (例如 plus: () => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined。
其实就是箭头函数绑定了父级作用域的上下文, 通俗点指向的就近使用的this指向
    window.a = 2;
    function setNum(){
        this.a = 1
    }
    setNum()
    new Vue({
        el: '#wrap',
        data:{
            
        },
        methods:{
            switchPhone:()=>{
                console.log(this)   //这样的话指向的this指向的是window  同理别的也一样
            }
        }
    })

method里不要使用箭头函数,箭头函数绑定的是父级作用域,并不会指向vue根实例,就换成这样就可以了

switchPhone(){
                //console.log('切换手机版');
                document.getElementsByClassName('phone_home_middle')[0].style.width = '150px';
                this.isPhoneFooter = true;
            }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题