watchListeners 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 datacountVariable, 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 executionthis.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 indeepProperty, 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 modificationqueryListAny 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 listenqueryList.nameThe change in theta, for thetaqueryList.countWe 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.idListen, and then call the corresponding interface to get the data, of course increatedormountedLife cycle, but we can do the same thing with watch, and that’s with WatchimmediateProperty, set to true, will execute immediately after initialization, regardless of whether the value has changedhandlermethods
watch:{
  '$route.query.id': {handle(newValue,oldValue){
        //do something
      },
      immediate:true}},Copy the code