Solve the Pit of Calling Method in Vue watch

  • 2021-09-12 00:28:12
  • OfStack

This means that when watch calls the method in methods, the page often reports that the method cannot be found

At this time, 1 must output 1 this in watch,

See if the shell wrapped by this has many layers, so I can't find a way, although I still don't understand why there are sometimes one or several layers of shells.

For example

It can be called normally with this. functionname ().

But in some cases (I haven't found the reason yet), when the console outputs this, you will find that the data is often wrapped in a {name}, and name also wraps 1 layer on your methods, so when using the method, it will become this. a. methods. funtionname ()

The reason is still being found, but the solution should be written down first.

Additional knowledge: Best practices for using Vue-do not call methods in "created" and "watch"

I won't talk too much, let's just look at the code ~


watch: { 
      params: {
        handler: function (val, oldVal) {
          if (val == '1') {
            this.initTableData()
          }
        },
        deep: true
      },
      property: {
        immediate: true,
        handler: function (val, oldVal) {
          this.initTableData()
        },
      },
    },

One common mistake Vue developers make is that they call methods unnecessarily in created and watch. The idea behind this is that we want to run watch as soon as the component is initialized.

//Bad practices created: () {this. handleChange ()}, methods: {handleChange () {//stuff happens}}, watch () {property () {this. handleChange ()}}

However, Vue provides a built-in solution for this, which is an Vue watch attribute that we often forget.

All we have to do is reorganize watch slightly and declare two properties:

1. handler (newVal, oldVal)-This is our watch method itself.

2. immediate: true-means that if it is declared in wacth, it will immediately execute the handler method in it. If it is false, it will be the same as our previous effect 1, and will not be executed when binding


//  Good practice 
methods: {
 handleChange() {
  // stuff happens
 }
},
watch () {
 property {
  immediate: true
  handler() {
   this.handleChange()
  }
 }
}

Related articles: