2017-04-10 38 views
0

方法之間的這個變量和創建的區別是什麼?這些方法和創建之間有什麼不同?

如果我想改變方法'handleCurrentChange中的全局變量personas,apis,total,那麼我必須保存這個上下文。

但是爲什麼我可以直接在創建時使用它?

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; 
      }); 
     } 
    }); 

回答

0

如果你想在這些功能的使用this,你可以簡單地使用箭頭功能(ES6,不具體到vuejs):

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

瞭解更多關於arrow functions

相關問題