A
A
arsenalfangun2020-11-08 13:05:34
JavaScript
arsenalfangun, 2020-11-08 13:05:34

Why is Vue data written this way?

Why is the data object enclosed in parentheses? Why can't it be done like this: data: {} or data: () => {}
5fa7c27b5b4c7200236670.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Gololobov, 2020-11-08
@arsenalfangun

Inside Vue, data is called as a function. Those. at the moment when vue is ready to access the data parameters, the following call occurs:
data()
Accordingly, a direct access to data declared as an object ( data: {} ) will cause an Uncaught TypeError: data is not a function error.
Now for the second option. data: () => {} - 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 the arrow function, we are left using two options in essence:
Short notation: Extended notation:
data: () => ({ param: 1 }) //Возвращает объект

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

If there are many unclear points, you can try to read this article

S
Sergey delphinpro, 2020-11-08
@delphinpro

Because the Vue documentation even puts it in a separate subsection: the data property in components should be a function that returns a data object .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question