Preface
Vue provides a more general method to respond to data changes through the watch option. This method is most useful when it is necessary to perform asynchronous or overhead operations when data changes.
1. Basic usage of listeners
<div >{{ fullName }}</div>
var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { = val + ' ' + }, lastName: function (val) { = + ' ' + val } } })
The purpose of this code is to listen for firstName and fullName, and when they change, the value of fullname is changed.
2. Listener format
Listener in method format
- Disadvantage 1: It cannot be automatically triggered when you first enter the page!
- Disadvantage 2: If the listening object is an object, if the property in the property changes, the listener will not be triggered!
Listener in object format
- Benefit 1: It can be automatically triggered when you just enter the page!
- Benefit 2: It can realize deep monitoring, that is, whether the properties in the listening object change!
3. Implement the triggering of monitoring and deep monitoring as soon as you enter the page
It triggers monitoring as soon as it enters the page
Implemented by adding the immediate option
const vm = new Vue({ el: '#app', data: { info: { username: 'admin' } }, watch:{ info:{ handle(newVal){ (newVal) }, // The monitoring is triggered as soon as it enters the page immediate: true } } })
In-depth monitoring
In the above code, when the username changes, we cannot listen successfully, because the change is the value of the object attribute, so deep listening is required, and the deep option is added
const vm = new Vue({ el: '#app', data: { info: { username: 'admin' } }, watch:{ info:{ handle(newVal){ (newVal) }, // The monitoring is triggered as soon as it enters the page immediate: true, // Implement deep listening. As long as any attribute in the object changes, "object listening" will be triggered deep: true } } })
Deep listening returns the value of the sub-property of the listening object
The execution result in the above code is to print the info object. It is still quite troublesome to add the username value we want to print. In fact, we can directly listen to and print the value of the changed sub-properties. We just need to add a layer of single quotes outside the sub-properties to be monitored:
const vm = new Vue({ el: '#app', data: { info: { username: 'admin' } }, watch:{ '': { handle(newVal){ (newVal) } } } })
at last
⚽This article introduces the basic use of listeners in Vue and how to implement in-depth monitoring. I hope you will gain some benefits after reading~
This is the end of this article about the basic usage of listeners in Vue. For more related content on the usage of Vue listeners, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!