简体   繁体   English

对 vuejs-templates webpack-simple 代码片段感到困惑

[英]Confused about vuejs-templates webpack-simple code snippet

I am a newbie of javascript.我是javascript的新手。

Start to learn Vue.js by reading the examples.通过阅读示例开始学习 Vue.js。

But I am confused about the code snippet of vuejs-templates/webpack-simple .但是我对vuejs-templates/webpack-simple的代码片段感到困惑。

From line 25第 25 行

  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }

I am wondering why code can't be written like this我想知道为什么代码不能这样写

  data: () => {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }

I have tried both code, the same result.两种代码我都试过了,结果一样。

I can't understand from reading Vue.js document.我无法通过阅读 Vue.js 文档来理解。

Please help me to understand this code snippet.请帮助我理解这个代码片段。

Thank you for taking time reading my problem.感谢您花时间阅读我的问题。

The question is not about why it isn't , but more about why should it .问题不在于为什么不这样做,而更多地在于为什么应该这样做

In both cases, you are defining a function, which is member of an object literal.在这两种情况下,您都在定义一个函数,它是对象文字的成员。 In es6 there is the feature of method properties , which is used as a shorthand notation.es6中有方法属性的特性,它被用作简写符号。 See also MDN .另请参阅MDN

I'd suggest you to take care when you want to use arrow functions over the method properties.当你想在方法属性上使用箭头函数时,我建议你小心。

Arrow functions provides the lexical this so sometimes you could find yourself in situation where this doesn't refer to correct context (It should be Vue object itself but it pointent to parent object, in your case probably window).箭头函数提供了词法this所以有时你会发现自己处于this没有引用正确上下文的情况(它应该是 Vue 对象本身,但它指向父对象,在你的情况下可能是窗口)。

VueJS Docs gives pretty same warning: VueJS Docs 给出了相同的警告:

Don't use arrow functions on an instance property or callback (eg vm.$watch('a', newVal => this.myMethod())).不要在实例属性或回调上使用箭头函数(例如 vm.$watch('a', newVal => this.myMethod()))。 As arrow functions are bound to the parent context, this will not be the Vue instance as you'd expect and this.myMethod will be undefined.由于箭头函数绑定到父上下文,这将不是您期望的 Vue 实例,并且 this.myMethod 将是未定义的。

https://v2.vuejs.org/v2/guide/instance.html#Properties-and-Methods https://v2.vuejs.org/v2/guide/instance.html#Properties-and-Methods

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM