解决Vue报错Error in callback for immediate watcher “height“: “TypeError: Cannot read properties of

1.Background

Recently, I encountered a problem in the project. The console reported an error Error in callback for immediate watcher "height": "TypeError: Cannot read properties of undefined (reading 'style')". After searching for a long time, I didn't know where the error was. Finally, I finally Solved, so record it.

The console reports an error as shown below

This error was reported inexplicably. It neither told you the specific location nor where the error occurred. The page and data were displayed normally, so I searched and searched, and finally found out where the problem was.

2.Business scenario

The code is to set a height for the table, but I assigned height to be empty in the data. Please see the code below for details.

 

 

This involves the life cycle functions in vue and the order of execution. Vue first gets the data in data, and then executes the functions in created and mounted. However, I assigned height to be empty. When Vue gets the data in data, it is empty, so an error will be reported, and it will be executed later. When calculating the height in mounted, it only assigns a value to height. So the console will report an error first, and then get the height you set for it when rendering, and the page can be displayed normally.

Here, the height should be assigned the value auto, that is, height: "auto", and this error will not be reported. However, in view of the optimization and standardization of the code, a more standardized and concise method was changed.

 

The optimized method can be completed in two steps. There is no need to declare it in the data. The height calculation function is placed in the computed calculation attribute and the problem of console error reporting is also solved. 

 

Guess you like

Origin blog.csdn.net/m0_59360516/article/details/127996352