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

Windows Service 2016 Datacenter\Stand\Embedded Activation Method (2021)

Run cmd with administrator privileges slmgr /ipk ...

Webservice remote debugging and timeout operation principle analysis

WebService Remote Debugging In .NET, the remote d...

How to use dl(dt,dd), ul(li), ol(li) in HTML

HTML <dl> Tag #Definition and Usage The <...

Detailed graphic explanation of MySql5.7.18 character set configuration

Background: A long time ago (2017.6.5, the articl...

JavaScript data flattening detailed explanation

Table of contents What is Flattening recursion to...

Docker cleaning killer/Docker overlay file takes up too much disk space

[Looking at all the migration files on the Intern...

Window.name solves the problem of cross-domain data transmission

<br />Original text: http://research.microso...

Element sample code to implement dynamic table

Table of contents 【Code background】 【Code Impleme...

A detailed introduction to wget command in Linux

Table of contents First install wget View Help Ma...

Native JS to achieve book flipping effects

This article shares with you a book flipping effe...

Example method of deploying react project on nginx

Test project: react-demo Clone your react-demo pr...

CSS to achieve Cyberpunk 2077 style visual effects in a few steps

background Before starting the article, let’s bri...

JavaScript implements constellation query function with detailed code

Table of contents 1. Title 2. Code 3. Results IV....

Write a mysql data backup script using shell

Ideas It's actually very simple Write a shell...

Solution to multiple 302 responses in nginx proxy (nginx Follow 302)

Proxying multiple 302s with proxy_intercept_error...