Can't anonymous functions in vue access the data defined in data?

An anonymous function is defined in

methods, which displays undefined
code when accessing data in data as follows:

        var vm = new Vue({
            el:"-sharproot",
            data:{
                show:true
            },
            methods:{
                handleclick:function() {
                    console.log(this.show);
                    var timer = function() {
                        console.log(this.show);
                    }
                    timer();
                }
            }
        })

console screenshot:

clipboard.png

May.16,2021

Please use the arrow function instead, or the direction of this will change


the parent object of this anonymous function is hade, which is not a vue instance. There are many solutions, such as the pointed function mentioned above, or modify the parent object, or save the external this to introduce calls for variables


            handleclick:function() {
                let that = this;
                var timer = function() {
                    console.log(that.show);
                }
                timer();
            }

. The this point in the function defined by

function will be changed, so the this is no longer pointing to the vm instance.
can be changed to any of the following ways

handleclick:function() {
    console.log(this.show);
    const that = this;    // thisvm
    var timer = function() {
        console.log(that.show);
    }
    timer();
}
handleclick:function() {
    console.log(this.show);
    var timer = function() {
        console.log(vm.show);    // vm
    }
    timer();
}
handleclick:function() {
    console.log(this.show);
    var timer = () => {        // this
        console.log(this.show);
    }
    timer();
}
Change the

to the arrow function, and the this points differently () = > {}


you need to cache this


your current this should point to window,. There are many ways to bind the this, of timer. Call, apply, bind, arrow function, etc.


shouldn't it be this.data.show


your handleclick should use the arrow function otherwise there is a problem with this pointing. In the future, it is better to use arrow function , the new ES6 feature

Menu