background

I recently took over front-end code written by someone else, and I’ve been filling in the holes for two weeks. Created hooks and asynchronous requests. After an hour of testing, we finally found out how synchronous and asynchronous requests affect the order of hook execution.

Conventional thinking to write the code, really do not see the problem, but a running problem, or worth investigating.

Functional description

There is a main page for administrative functionality, which is broken down into four sub-components:

  1. ChartsComp: Some statistics at the top
  2. SearchComp: Intermediate condition area
  3. BtnComp: Middle operation button area
  4. DataTableComp: List of data at the bottom, with a column showing flag images based on country names

The XXXHome created hook in the main interface initializes data needed by other components:

There is no data change of Watch in the sub-component

The predecessor of the code wants to get all the data in the Home page, which is then listened on and used by the child component using Watch. The first problem occurs with getChartData, where the child component references and data use are as follows:

Created execution order of parent and child components

Add the print information to the created of the parent component in the following order:

That is, from father to son

However, if you call the created drawing method directly in the sub-component, the problem of incomplete data will occur, and it is sporadic, which has not been explored in detail due to the limited time.

The safest solution: add a flag to Home, add a V-if flag to all sub-components that rely on asynchronous request data, wait for the data to come back and correct to true, then render the sub-component v-if=”isDataOk”.

Component unassembly, if it’s just to reduce the amount of code on the main page without reuse, such as the ChartsCmop in this article, can put the data request in its own Created and don’t need to rely on the parent component to pass in, and this won’t be a problem.

BeforeCreated and created sequence

I encountered a problem yesterday. After testing, I found that if beforeCreated is defined as async, the code behind “await” will be executed after the “created” execution. I felt a little subversive of the official introduction, so I studied it.

BeforeCreate (” created “, “await”); “beforeCreate (” created”, “await”);

First, again, this feature, the bottom data list, needs to display the flag image by country name. Create (‘ create ‘, ‘create’, ‘create’, ‘create’); create (‘ create ‘, ‘create’, ‘create’, ‘create’);

The Created method is executed while it waits for the result of the request response

In this case, this.areas is still the default empty array, and the Created getDataTable method gets the data needed by DataTableComp and completes the rendering of the child components:

<span  :title="scope.row.countryName">
       <el-image :src="getCountryImg(scope.row.countryName)"  class="flagImg"/>
       {{ scope.row.countryName}}
 </span>
Copy the code

Fourth, getCountryImg uses countries and raises an error. As it renders, it retrieves the flag image, looks for countryName, and if not, displays the image of the first element Contries [0] :

getCountryImg(country) {
      for (let i = 0; i < this.contries.length; i += 1) {
        const item = this.contries[i];
        if (item.nameZh === country) {
          return`data:image/jpeg; base64,${item.img64}`; }}return`data:image/jpeg; base64,${this.contries[0].img64}`;
    },
Copy the code

Finally, since the beforeCreate method has not ended when the DataTableComp is drawn, the countries passed by the parent component is an empty array, and this. Contries [0] raises an exception for undefined:

Solution: Add the isAreaOk flag
data-table-comp v-if="isAreasOk"

The revelation of

This article introduces the implementation of the Created and beforeCreate hooks in Vue.

  1. The created method of the parent component is executed sequentially. Even if there are asynchronous requests in the parent component’s Created method, it will wait for the end of all asynchronous requests before executing the created method of the child component.
  2. The beforeCreate method of the same component executes before the Created method. If the beforeCreate returns a Promise object with await in it, the main process does not process it and executes the Created method instead.

For the second point, although beforeCreate is defined as async, Vue should be called without await beforeCreate(), which is asynchronous logic in nature. So instead of waiting for it to actually complete, the subsequent created execution continues and its await goes into the callback function waiting queue.

Some knowledge about Vue development, the author has a long article in detail, interested friends can see this article “five Vue development collection”.