After formatting the data, NaN appears on the page
Purpose
In a vue project, the timestamp of the returned data needs to be formatted, and the data format is as follows
res = [ { "program_id": 6, "code": 1005,"create_time": 1627022366, "child": [ { "program_id": 7, "code": 1006, "create_time": 1627022366,} ] } ]
question
Formatted using recursion, execute in computed. There is no problem with the first display, but after switching the page, the time display becomes one line of NaN
formatProjectList (list) { let projectList = ((item) => { // formatTime is a format function that returns a string in the format 'Y-m-d H:i:s' item.create_time = formatTime(new Date( item.create_time * 1000 ), 'Y-m-d H:i:s') if () { () } return item }) return projectList },
reason
In the map function, item.create_time directly modifys the source data res, which is a completed string that has been formatted.
Switching the page will trigger computed again. At this time, performing formatting will pass the string to the formatTime formatting function. If formatTime receives the string, it will return NaN.
Solution
Deeply copy the source data res, and then execute the function
computed: { projectList () { // deepClone is a deep copy function let newList = deepClone() let formatList = (newList) return formatList } }
Sometimes NAN occurs when numerical operations are
In the html of vue, it is often the case that the data obtained needs to be added, subtracted, multiplied and divided. If the data is operated in the expression, it is necessary to perform addition, subtraction, multiplication and division.
example:{{ a + b + c }}
This will cause, when you get the data, the value has not been retrieved, and the dom has just started rendering, so the values of a, b, and c will perform operations and display the NAN. The calculation result will not be displayed until the data acquisition is completed. For this short-term NAN flash, it will often affect the user experience
Provide specific solutions
One is to add loading, overwrite the NAN through loading, and the other is to directly assign the value in the result of the http request.
like:
= + +
Note: The result here must be defined in the data attribute, otherwise an error will be reported.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.