What is the different this between methods and created?

时间:2017-04-10 02:22:41

标签: vuejs2

What is the difference of this variable between methods and created?

If I want to change the global variable personas,apis,total in methods' handleCurrentChange, then I have to save the context this.

But why can I directly use this in created?

var vue = new Vue({
        el: "#app",
        personas: {},
        apis: {},
        total: '',
        methods: {
            submitForm: function(formName) {
                var _this = this;
                this.$refs[formName].validate(function(valid) {
                    if (valid) {
                        console.log('form validate successfule.');
                    } else {
                        console.log('form validate failed.');
                    }
                });
            },
            handleCurrentChange: function (val) {
                var _this = this;
                this.$http.post('/persona/index', {
                    current: val,
                    size: this.pageSize
                }, {emulateJSON: true}).then(function (response) {
                    _this.personas = response.body.data.personas;
                    _this.total = response.body.data.total;

                }, function (response) {
                   console.log('Sorry, there's no response.');
                });
            }
        },
        created: function () {
            this.$http.get('/persona/index').then(function (res) {
                this.personas= res.body.data.personas;
                this.total = res.body.data.total;
                this.apis= res.body.data.apis;
            });
        }
    });

1 个答案:

答案 0 :(得分:0)

如果你想在这些函数中使用this,你可以简单地使用箭头函数(ES6,不是特定于vuejs):

this.$refs[formName].validate(valid => {
   // you can use 'this' here
}); 

详细了解arrow functions

相关问题