The usage of vue watch is: 1. When the fullName value changes, the watch listens and executes; 2. The watch executes the handler method and immediate attribute; 3. Use the deep attribute, deep monitoring, and the attributes below the commonly used object Change.
[Related article recommendations: vue.js]
vue watch usage is:
1. Basic usage:
When the fullName value changes, watch monitors and executes
<div> <p>FullName: {{fullName}}</p> <p>FirstName: <input type="text" v-model="firstName"></p> </div> new Vue({ el: '#root', data: { firstName: 'Dawei', lastName: 'Lou', fullName: '' }, watch: { firstName(newName, oldName) { this.fullName = newName + ' ' + this.lastName; } } })
2. Handler method and immediate attribute
The above example is that the watch is only executed when the value changes. We want the watch to be executed when the value is initially used, so we use the handler
and immediate
attributes
watch: { firstName: { handler(newName, oldName) { this.fullName = newName + ' ' + this.lastName; }, // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法,如果设置了false,那么效果和上边例子一样 immediate: true } }
3. deep attribute (deep monitoring, change of attributes below the commonly used object)
<div> <p>obj.a: {{obj.a}}</p> <p>obj.a: <input type="text" v-model="obj.a"></p> </div> new Vue({ el: '#root', data: { obj: { a: 123 } }, watch: { obj: { handler(newName, oldName) { console.log('obj.a changed'); }, immediate: true } } })
When we entered the data view in the input box to change the value of obj.a, we found that it was invalid. Due to limitations of modern JavaScript (and the deprecation of Object.observe), Vue cannot detect the addition or removal of object properties. Since Vue performs the getter/setter conversion process on the property when initializing the instance, the property must exist on the data object in order for Vue to convert it so that it is responsive.
By default, the handler only listens for changes in the reference of the obj attribute. It will only listen when we assign a value to obj. For example, we reassign obj in the mounted event hook function:
mounted: { this.obj = { a: '456' } }
So what do we need to monitor the value of attribute a in obj? This is when the deep attribute comes in handy:
watch: { obj: { handler(newName, oldName) { console.log('obj.a changed'); }, immediate: true, deep: true } }
This method has a great impact on performance. Modifying any attribute in obj will trigger the handler in the listener. We can do the following processing:
watch: { 'obj.a': { handler(newName, oldName) { console.log('obj.a changed'); }, immediate: true, // deep: true } }
I won’t go into detail about the logout of the watch here. In actual development, the watch will be destroyed along with the component.
Related free learning recommendations: javascript (video)
The above is the detailed content of What is the usage of vue watch?. For more information, please follow other related articles on the PHP Chinese website!