How to correctly define this pointing in Vue?

problem description

The definition of self = this in

Vue created points to the current vue instance, but the use of self in methods does not point to the current instance correctly.

related codes

new Vue({
    el: "-sharpvue",
    data: {
        col: "dd"
    },
    created: function () {
        self = this
    },
    methods: {
        render: function() {
            jQuery.get(ajaxurl, function (res) {
                self.dd = "ee"
            })
        }
    }
})

 self.dd  data col 

 new Vue({}) data  col: "dd"
 self.dd  vue 
Jan.23,2022

in strict mode, this kind of global variable is not recommended. If you want to write this, I guess you can

.
var instance=new Vue({
    el: '-sharpvue',
    data: {
        col: 'dd'
    },
    created: function () {
        instance= this
    },
    methods: {
        render: function() {
            jQuery.get(ajaxurl, function (res) {
                instance.dd = 'ee'
            })
        }
    }
})

look at your way of development, it should be written directly to js, but it is recommended to use the .vue file constructed by vue's cli to develop.

The this in methods of
vue automatically executes the vue instance by default, so the same logic can also declare a self variable store this in methods .


is 8012 years old, why not use the arrow function.

Menu