sample code
A data list is defined, which is an empty array by default.
An API request is defined, and getDat
also defines two life cycle hooks created and mounted
Analyze the situation in created
At this time, we can successfully send the API request to get the data, and the console will print created, mounte
First of all, we know: created and mounted are both synchronous, and api requests are asynchronous
So the final process is this:
created -- api请求 -- 获取数据 -- 组件重新渲染
-- mounted -- 组件首次渲染
In other words, after sending the API request, two branches will be generated, and the code logic is confusing
Let's analyze the situation in mounted
This is the process:
created – mounted – component renders for the first time – api request – gets data – component re-renders
Summarize
I tend to put it in mounted. In fact, there is not much difference, but the overall logic will be clearer in mounted.
But I also saw that some people said that it should be placed in created to help consistency ssr does not support beforemount mounted