watch
Listeners are used to listen for changes in variables and then write operations to the hook function.
1. Listening for common variables
- For example, if you want to use data
count
Variable, which has two callback arguments, one for the new value and one for the old value, i.eThe values after and before the change
export default {
name: "Test".data(){
return{
count:0,}},watch: {count(newValue,oldValue){
//do something}}},Copy the code
2. Listen for objects
- If we’re listening on an object, we’ll find execution
this.queryList.name='jack'
, cannot trigger the monitoring of the Watch
export default {
name: "Test".data(){
return{
queryList: {count:0.name:' ',}}},watch: {queryList(newValue,oldValue){
//do something}}},Copy the code
- That’s where it comes in
deep
Property, the listener is going to go down the layers, add this listener to all the properties of the object, but then the performance overhead is going to be huge, any modificationqueryList
Any one of these properties will trigger this listenerhandler
.
export default {
name: "Test".data(){
return{
queryList: {count:0.name:' ',}}},watch: {queryList: {handle(newValue,oldValue){
//do something
},
deep:true,}}}Copy the code
- But sometimes, let’s say I just want to listen
queryList.name
The change in theta, for thetaqueryList.count
We don’t need to listen, so we can write it as follows. We can only listen on a particular property of the object and it will give us more performance improvement than listening on the whole object
export default {
name: "Test".data(){
return{
queryList: {count:0.name:' '}}},watch: {'queryList.name': {handle(newValue,oldValue){
//do something,}}}},Copy the code
3. The listener is triggered immediately upon the first binding
- For example, the article details page renders the corresponding article details according to the article ID, by routing the information
$route.query.id
Listen, and then call the corresponding interface to get the data, of course increated
ormounted
Life cycle, but we can do the same thing with watch, and that’s with Watchimmediate
Property, set to true, will execute immediately after initialization, regardless of whether the value has changedhandler
methods
watch:{
'$route.query.id': {handle(newValue,oldValue){
//do something
},
immediate:true}},Copy the code