Why is data written this way in Vue?

  • 0
    What is the data object in parentheses for? Why can't you do this: data: {} or data: () = & gt; {}
    JavaScript Anonymous, Dec 19, 2019

  • 2 Answers
  • 0
    Within Vue, data is called as a function. Those. at the moment when vue is ready to access the data parameters there is a call like this:

    data ()

    Accordingly, direct access to data declared as an object ( data: {} ) will cause an error Uncaught TypeError: data is not a function.

    Now about the second option. data: () = & gt; {} - such a declaration implies that there will be some conditions inside the {} block.

    And after calling the data () function, vue expects to receive an object as a result.

    When using an arrow function, we are left with two options in essence:

    Short entry:

    data: () = & gt; ({param: 1}) // Returns an object

    Extended recording:

    data: () => {
    return {
    param: 1

    If you have a lot of unclear points, you can try reading this article

  • 0
    Because the Vue docs even put it in a separate subsection: the data property in components should be a function that returns a data object .

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!