Vuejs - data: or data()?

Jul 30, 2018 vuejs laravel data option undefined
WhatsApp
Do you get an undefined value when printing the data from a component? Spent a few hours debugging this on a codepen I’m working on for my portfolio. As I’m passing an array to a child component I was outputting an undefined array for the child’s property - xValues/yValues.

As it so happens, there’s difference between using data: and data(). I noticed the syntax but I wasn't sure of the difference and what effect it had. What I began to discover was the scope of the variables and my properties no longer existed. Why did these variables return undefined. It was a mixture of understanding components, scope and objects.

Looking at the link provided in 1.b, it becomes clearer understanding that each object has a unique signature. That’s how many languages identify and perform logical operators to match objects with each other. We must supple the data option a function if it is a component’s data. When data is of the root, we can provide it without since there is only ever one copy of the root instance.

i.e.
(shorthand) data() { return {//my variables } }
data: function() {return { //my variables } }.

tldr;
Use without function for root, but you must apply the function() to the data option in a component.

Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions about short and standard notations.


References
1.a https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function
1.b https://stackoverflow.com/questions/48176345/what-is-difference-between-data-and-data-in-vue-js

Supplementary Reading
https://stackoverflow.com/questions/48980865/vue-js-difference-of-data-return-vs-data
https://laracasts.com/discuss/channels/vue/what-is-the-difference-between-data-data-function

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb