为什么即使使用Arrow函数,Vue方法中的窗口对象也是如此

时间:2018-07-30 02:32:15

标签: vue.js

我有一个简单的Vue app,看起来像这样...

new Vue({
  el: "#app",
  data: {
    value:""
  },
  mounted: function(){
    this.test(10);
  },
  methods: {
    test: (max) =>{
        console.log(this)
    }
  }
})

控制台输出窗口,我希望它是Vue应用程序。我如何构造它以使其成为Vue?

1 个答案:

答案 0 :(得分:2)

[^]在您的箭头功能中特别是this

使用普通的window声明或等效的ES2015 method declaration shorthand

function
new Vue({
  el: "#app",
  data: {
    value: "test"
  },
  mounted: function() {
    this.test(10);
    this.test2(42);
    this.test3(42);
  },
  methods: {
    // Arrow function: `this` is the context when declaring.
    test: (max) => {
      console.log(this === window)
    },
    // Function expression: `this` is the context when calling.
    // Bound to the Vue instance by Vue.
    test2: function(max) {
      console.log(this.value);
    },
    // ES6 method shorthand, same as above.
    test3(max) {
      console.log(this.value);
    }
  }
});