Detailed explanation of Vue monitoring properties


In Vue, you can use the watch/$watch method to monitor changes in data, computed properties, events, and routes, so as to realize functions such as data binding, event monitoring, and routing control. It is necessary to select an appropriate monitoring method according to the actual situation to avoid excessive monitoring or monitoring of unnecessary attributes, thereby improving application performance and user experience.

Define the properties to listen to

Define the property to listen to: "message" is initially set to "Hello, Vue!"

data() {
    
    
  return {
    
    
    message: 'Hello, Vue!'
  }
}

define watch

In the following example, a watch attribute named "message" is defined, which monitors the change of the "message" attribute, and outputs the value before and after the change when it changes

watch: {
    
    
  message(newValue, oldValue) {
    
    
    console.log('message changed from', oldValue, 'to', newValue)
  }
}

Modify the monitored attribute value

Change the value of the "message" attribute from "Hello, Vue!" to "Hello, World!"
Since we have defined the listener function in the watch attribute, when the attribute value changes, the watch function will be called and output Value before and after the change

this.message = 'Hello, World!'

The parameters of the watch function include newValue and oldValue, which represent the new value and old value of the attribute respectively.
In the watch function, corresponding operations can be performed according to these parameters, such as sending network requests, updating views, etc.

In addition to monitoring a single property, Vue also supports monitoring changes in multiple properties and deep monitoring properties.
These functions can be realized by setting the deep monitoring option and immediate option in the watch property

watch: {
    
    
  // 监听多个属性
  'message': function (newValue, oldValue) {
    
     /* ... */ },
  'firstName': function (newValue, oldValue) {
    
     /* ... */ },
  'lastName': function (newValue, oldValue) {
    
     /* ... */ },

  // 深度监听属性
  'user.profile': {
    
    
    handler: function (newValue, oldValue) {
    
     /* ... */ },
    deep: true
  },

  // 立即调用监听函数
  'message': {
    
    
    handler: function (newValue, oldValue) {
    
     /* ... */ },
    immediate: true
  }
}

Listen for array changes

To listen for array changes, use the watch or $watch methods.

data() {
    
    
  return {
    
    
    items: [1, 2, 3]
  }
}

Use the watch method to monitor array changes:
when the array changes, the watch function will be called and output the values ​​before and after the change

watch: {
    
    
  items: function (newValue, oldValue) {
    
    
    console.log('items changed from', oldValue, 'to', newValue)
  }
}

It should be noted that watch can only monitor the length change of the array and the call of the $set method, but not the change of the array elements.
If you need to monitor the changes of the array elements, you can use the $watch method provided by Vue. For example:

created() {
    
    
  this.$watch('items', function (newValue, oldValue) {
    
    
    console.log('items changed from', oldValue, 'to', newValue)
  }, {
    
     deep: true })
}

Use the watch method to monitor the changes of the array, and set the depth monitoring option. Since the elements of the array are also responsive, when the array elements change, the watch method monitors the changes of the array, and set the depth monitoring option. Since the elements of the array are also responsive , so when an array element changes,The w a t c h method monitors the changes of the array and sets the depth monitoring option. Since the elements of the array are also responsive, the watch function will also be called when the array elements change.

Listen for object changes

In addition to arrays, objects in Vue are also responsive, and you can use the watch or $watch method to monitor changes in objects

data() {
    
    
  return {
    
    
    user: {
    
    
      name: 'Tom',
      age: 18
    }
  }
}

We can use the watch method to monitor object changes:

watch: {
    
    
  'user.name': function (newValue, oldValue) {
    
    
    console.log('user.name changed from', oldValue, 'to', newValue)
  },
  'user.age': function (newValue, oldValue) {
    
    
    console.log('user.age changed from', oldValue, 'to', newValue)
  }
}

If the property of the object is added dynamically, the watch method may not be able to monitor the change of the property.
At this time, the $watch method can be used to monitor the dynamic property. For example:

created() {
    
    
  this.$watch('user', function (newValue, oldValue) {
    
    
    console.log('user changed from', oldValue, 'to', newValue)
  }, {
    
     deep: true })
}

Monitor computed property changes

A computed property is a special property whose value is calculated from other properties

computed: {
    
    
  fullName() {
    
    
    return this.firstName + ' ' + this.lastName
  }
}

The value of the computed attribute is calculated based on other attributes, so if the monitored attribute changes, the value of the computed attribute will also change, thereby triggering the call of the watch function. If you do not need to monitor the change of the attribute, you can use the computed attribute to
define Ordinary computed properties, not listener computed properties

watch: {
    
    
  fullName: function (newValue, oldValue) {
    
    
    console.log('fullName changed from', oldValue, 'to', newValue)
  }
}

Listen for event changes

Components can trigger custom events through the $emit method. If you want to monitor changes in events,
you can use the $on method.
Define a custom event named "my-event", and use the $emit method in the method to trigger the event, and pass the parameter "hello"

<template>
  <button @click="onClick">Click me</button>
</template>

<script>
export default {
    
    
  methods: {
    
    
    onClick() {
    
    
      this.$emit('my-event', 'hello')
    }
  }
}
</script>

Use the $on method to listen to custom events in the parent component:

<template>
  <div>
    <my-component @my-event="onEvent"></my-component>
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue'

export default {
    
    
  components: {
    
     MyComponent },
  methods: {
    
    
    onEvent(value) {
    
    
      console.log('event value:', value)
    }
  }
}
</script>

We use the @my-event attribute in the parent component to listen to the custom event and output the value of the event parameter in the method.
When the child component triggers the custom event, the method of the parent component will be called and output the value of the event parameter

It should be noted that the $on method can only be used in component instances and cannot be used in Vue instances.
If you need to listen to events in the Vue instance, you can use the $emit method to trigger the event, and use the $on method in the Vue instance to listen to the event.

Listen for route changes

Routing is a mechanism to control page jumps. If you want to monitor changes in routing, you can use the beforeRouteUpdate hook or route / route/ro u t e / watch method

const routes = [
  {
    
    
    path: '/',
    component: Home
  },
  {
    
    
    path: '/about',
    component: About  
  }
]

Two routes are defined: "/" and "/about". You can use the beforeRouteUpdate hook to monitor route changes:

export default {
    
    
  beforeRouteUpdate(to, from, next) {
    
    
    console.log('route changed from', from.path, 'to', to.path)
    next()
  }
}

Use the beforeRouteUpdate hook in the component to monitor the route change, and output the route path before and after the change in the console. It
should be noted that the beforeRouteUpdate hook can only be used in the component corresponding to the route

If you need to monitor routing changes in the Vue instance, you can use route / route/ro u t e / watch method:

export default {
    
    
  created() {
    
    
    this.$watch('$route', (to, from) => {
    
    
      console.log('route changed from', from.path, 'to', to.path)
    })
  }
}

Use the $watch method in the Vue instance to monitor the change of the $route property, and output the routing path before and after the change on the console

It should be noted that route / route/The ro u t e / watch method can only be used in the Vue instance, and cannot be used in the component corresponding to the route. If you need to monitor route changes in the component corresponding to the route, you can use the beforeRouteUpdate hook

Guess you like

Origin blog.csdn.net/weixin_43749805/article/details/130579582