Vue Basics Listener Detailed Explanation

Vue Basics Listener Detailed Explanation

What is a listener in vue

  • During development, we defined data in the object returned by data, and this data can be bound to template through interpolation syntax and other methods.
  • When the data changes, the data bound in the template will be automatically updated to display the latest data. However, this change is automatically monitored by the data value in the template.
  • In some cases, we want to monitor the changes of certain data in the code logic, then we need to use the listener watch

Official definition : Vue provides a more general method to respond to data changes through the watch option. This approach is most useful when you need to perform asynchronous or expensive operations when data changes.

An object where the keys are the reactive properties to listen to - either containing data or computed properties - and the values ​​are the corresponding callback functions. The value can also be a method name, or an object containing additional options. The component instance will call $watch() when instantiated. See $watch for more information about the deep, immediate and flush options.

Usage of Listener

Option: watch

Type: { [key: string]: string | Function | Object | Array}

Configuration options for the watch listener:

By default, watch only listens to changes in data references and does not respond to changes in internal properties of the data:

At this time, we can use an option deep to listen more deeply; another property is that we hope to execute it immediately at the beginning: at this time, we use the immediate option; at this time, no matter whether the data changes later, the listening function will be executed once;

Contents of data:

data() {
    return {
        info:
            name: 'cgj'
        }
    }
}
watch:
    info:
        handler(newValue, oldValue) {
            console.log(newValue, oldValue)    
        }
        deep: true,
        immediate: true,
    }
}

Another thing that is not mentioned in the Vue3 documentation, but is mentioned in the Vue2 documentation is the properties of the listening object:

'info.name': function(newValue, oldValue) {
    console.log(newValue, oldValue)
}

Another way is to use the $watch API:

For more information about $watch, see the official API (less commonly used): Example method | Vue.js

const app = createApp({
  data() {
    return {
      a: 1,
      b: 2,
      c: {
        d: 4
      },
      e: 5,
      f: 6
    }
  },
  watch:
    // Listen to the top-level property
    a(val, oldVal) {
      console.log(`new: ${val}, old: ${oldVal}`)
    },
    // string method name b: 'someMethod',
    // This callback will be called when the property of any monitored object changes, no matter how deeply it is nested c: {
      handler(val, oldVal) {
        console.log('c changed')
      },
      deep: true
    },
    // Listen to a single nested property
    'c.d': function (val, oldVal) {
      // do something
    },
    // This callback will be called immediately after listening starts e: {
      handler(val, oldVal) {
        console.log('e changed')
      },
      immediate: true
    },
    // You can pass an array of callbacks and they will be called one by one f: [
      'handle1',
      function handle2(val, oldVal) {
        console.log('handle2 triggered')
      },
      {
        handler: function handle3(val, oldVal) {
          console.log('handle3 triggered')
        }
        /* ... */
      }
    ]
  },
  methods: {
    someMethod() {
      console.log('b changed')
    },
    handle1() {
      console.log('handle 1 triggered')
    }
  }
})
const vm = app.mount('#app')
vm.a = 3 // => new: 3, old: 1

vue listener-watch

Goal: Can listen to data/computed property value changes

grammar:

watch:
    "The name of the property being listened to" (newVal, oldVal){
    }
}

Example code:

<template>
  <div>
    <input type="text" v-model="name">
  </div>
</template>
<script>
export default {
  data(){
    return {
      name: ""
    }
  },
  // Goal: Listen for changes in name value/*
  grammar:
    watch:
      variable name(newVal, oldVal){
        // The variable name corresponding to the value changes here automatically triggered}
    }
  */
  watch:
    // newVal: current value // oldVal: previous value name(newVal, oldVal){
      console.log(newVal, oldVal);
    }
  }
}
</script>
<style>
</style>

Summary : To listen to a property change, use the watch method

Vue listener - deep listening and immediate execution

Goal: Can listen to data/computed property value changes

grammar:

watch:
    "The name of the property being listened to" (newVal, oldVal){
    }
}

Example code:

<template>
  <div>
    <input type="text" v-model="user.name">
    <input type="text" v-model="user.age">
  </div>
</template>
<script>
export default {
  data(){
    return {
      user: {
        name: "",
        age: 0
      }
    }
  },
  // Target: Listening object/*
  grammar:
    watch:
      variable name(newVal, oldVal){
        // The variable name corresponding to the value changes here automatically triggered},
      Variable name: {
        handler(newVal, oldVal){
        },
        deep: true, // deep listening (value changes in the object's inner layer)
        immediate: true // Listen immediately (handler is executed once when the webpage is opened)
      }
    }
  */
  watch:
    user: {
      handler(newVal, oldVal){
        //Object in userconsole.log(newVal, oldVal);
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style>
</style>

Summary : immediate listening, deep listening, handler fixed method triggering

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of the watch listener example in vue3.0
  • How to use watch listeners in Vue2 and Vue3
  • Basic usage examples of listeners in Vue
  • Summary of the use of Vue computed properties and listeners
  • Solve the problem of undefined when calling this in vue listener watch
  • Vue learning notes: calculation properties and listener usage
  • Vue 2.0 listener watch attribute code detailed explanation

<<:  How to use CSS pseudo-elements to control the style of several consecutive elements

>>:  The most detailed method to install docker on CentOS 8

Recommend

Practical explanation of editing files, saving and exiting in linux

How to save and exit after editing a file in Linu...

How to design and optimize MySQL indexes

Table of contents What is an index? Leftmost pref...

Implementation of CSS border length control function

In the past, when I needed the border length to b...

Simple setup of VMware ESXi6.7 (with pictures and text)

1. Introduction to VMware vSphere VMware vSphere ...

Solution to Docker disk space cleaning

Some time ago, I encountered the problem that the...

Building .NET Core 2.0 + Nginx + Supervisor environment under Centos7 system

1. Introduction to Linux .NET Core Microsoft has ...

How to use HTML+CSS to create TG-vision homepage

This time we use HTML+CSS layout to make a prelim...

CSS3 uses the transition property to achieve transition effects

Detailed description of properties The purpose of...

Detailed explanation of the specific use of the ENV instruction in Dockerfile

1. The ENV instruction in the Dockerfile is used ...

Summary of methods to prevent users from submitting forms repeatedly

Duplicate form submission is the most common and ...

Detailed Tutorial on Installing MySQL 5.7 on RedHat 6.5

RedHat6.5 installation MySQL5.7 tutorial sharing,...

MySQL uses aggregate functions to query a single table

Aggregate functions Acts on a set of data and ret...

JS implements a stopwatch timer

This article example shares the specific code of ...

Two ways to reset the root password of MySQL database using lnmp

The first method: Use Junge's one-click scrip...

JavaScript to achieve mouse drag effect

This article shares the specific code of JavaScri...