Vue is used to pre-load the image watch,
Watch application scenarios
I want to believe that image pre-loading has been touched by everyone. When there are a large number of images, we will display the homepage only to ensure that all the page images are loaded, perform some ajax requests or logical operations
Now, if you use computed to listen to a data and perform a series of logical operations and ajax requests, watch is no longer suitable. If you use computed, you cannot even implement it, only watch listeners
<Template> <div v-show = show> </div> </template> <script> export default {mounted () {var _ this = this let imgs = document. querySelectorAll ('img ') console. log (imgs) Array. from (imgs ). forEach (item) => {let img = new Image () img. onload = () => {this. count ++} img. src = item. getAttribute ('src')}, data () {return {count: 0, show: false }}, watch: {count (val, oldval) {if (val = 4) {this. show = true alert ("loaded") // you can then send some ajax operations to the background }}</script>
We can find that the page is displayed only when all four images are uploaded.
According to the end, there is a very important sentence.
Although computing attributes are more suitable in most cases, a custom watcher is also required. This is why Vue provides a more general method to respond to data changes using the watch option. This is useful when you want to perform asynchronous operations or overhead operations when data changes.
Based on this official understanding, I will summarize my overall understanding. Give a summary of computed and watch, remember the summary of these points, and think about these summary during the project, and select your application method.
Computed:
Listening to multiple data or one data for maintenance returns a status value. If one or more data changes, the whole function body is computed and the status value is returned.
Watch:
Only one listener is required. As long as the data changes, two parameters are returned. The first parameter is the current value, and the second parameter is the value before the change, it will trigger the logical behavior in the function body for subsequent logical operations.
The above vue pre-loaded watch usage examples are all the content shared by Alibaba Cloud. I hope you can give us a reference and support the help house.