Scene:The shopping cart increases the number of items and updates the total number of items on the bridge logo. If the current changed quantity is added only, the original quantity will be added again to cause calculation errors. Therefore, the quantity before the change is subtracted to obtain the added quantity.
Method 1: Watch directly to listen to data data
watch: { a (now,old) { (now,old) } }
old is the old value now is the updated value
Method 2: Customize the command
Through custom directives, bind the value before update to the dataset of the corresponding element of the custom directive and then obtain the element through ref in the vue file to obtain the old value
I won't say much about the custom commands. I have written a previous related blog. I will directly upload the code here.
Custom directives need to create a new js file and introduce vue source code package
import Vue from 'vue' /*Custom command*/ /* Object bound to el, parameters on binding directive*/ ('n',{ /*Triggered when inserting data*/ inserted: function (el,binding) { ('insert',binding,el) = }, update: function (el,binding) { ('Update parameters',binding) = = }, bind:function (el,binding) { ('Binding Parameters',binding) = } })
Used in .vue files
import n from '../assets/n' <div ref="div" v-n="a"></div> <button @click="inc">Increase</button> inc () { ++ var that = this setTimeout(function () { (that.$) },1) }
The inc here is for updating data operations, why should a timer be set?
Because the parameters are changed first and then the v-n instruction is triggered. If the timer is not added, the data obtained is the data updated last time.
Comparing the two methods, it is obvious that watch is more convenient but custom instructions are also a good thing. If you learn it, you may use it in other places in the future.
The above method of obtaining the value before and after the data data is changed is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.