Scenario description:
When I used vue to update data binding before, I found an inexplicable problem.
I declared an array property in a vue instance likebooks: []
, used in callback functions for asynchronous requests = ;
Change data, and the update step is printed immediately afterwards.()
, the print data is indeed updated successfully! But the page data rendering is{{}}
still{{books}}
No data is displayed! ! !
This made my head hurt, and it took me a long time to prove it repeatedly:The data must have been updated, but it's awesome
{{books}}
It just doesn't show it!
Tip: I'm at axiosCallback functionUsed inthisUpdate data!
Finally, I remembered a small detail. I used function expressions for axios asynchronous communication callback function.axios({xxx}).then(function(res){xxx})
, the format example is as follows:
axios({ url: url, method: "get", headers: { token: token }, //Custom request header data passing token params: { userId: userId } }).then(function(res) { //The above callback function uses the standard format } });
Use this format to write a callback function. If you use this in the callback function, then this this is not a vm(ViewModel) object, but the callback function itself! ! !
Therefore, using this callback function writing method, you cannot use similar in the callback function.Update data! Only use
(vm refers to the reference or object attribute name when creating a vue instance object) to update the vue object data.
If you want to use this to achieve data update, you must use the abbreviation format of the callback function:axios({xxx}).then((res)=>{xxx})
, the format example is as follows:
axios({ url: url, method: "get", headers: { token: token }, //Custom request header data passing token params: { userId: userId } }).then((res)=>{ //The abbreviation format used in the above callback function } });
Using this abbreviation format callback function writing method, you can use this directly in the callback function. At this time, this this is also a vm(ViewModel) object! ! !
PS: Well, there is no one else in this detail, and I blame myself for not paying attention to it. I used the standard format callback function writing~
But, by the way, why it is written in standard format, this does not refer to a vue instance object, but the data updated with it is likeIt has also been updated, and is there really no problem with printing it? ? ?
This is the end of this article about using this to update data in vue. This is the end of this article. For more related vue, use this to update data content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!