Recently, computed and Watch have been used in the project, and I feel like I want to summarize a wave of computed and watch.
computed
Now we need to display the name data, which is concatenated by lastName and firstName when using data directly:
<template>
<div>
<i>{{firstName + lastName}}</i>
</div>
</template>
Copy the code
data(){
return {
firstName: 'ky',
lastName: 'zon'
}
}
Copy the code
I feel good after writing like this. Mission accomplished! But if my name by firstName, secondName thirdName… Composition? It’s all in your beard? That’s redundant! We want to decouple! When using computed, you can do this:
<template>
<div>
<i>{{name}}</i>
</div>
</template>
Copy the code
data(){ return { firstName: 'ky', lastName: 'zon' } } computed: { name(){ return this.firstName + this.lastName; }}Copy the code
Complex data processing can be put in JS.
watch
Now there is a requirement to execute a piece of complex business logic as soon as the name data is updated
data(){
return {
name: 'zonky'
}
}
Copy the code
Of course, if I am diligent and careful, I will update the name of each place like this:
This. name = 'zhuge '; // This is business logicCopy the code
But in this case, can I still hold my patience during debug? So we use watch:
Watch: {name(newVal){// Add complex business logic like asynchronous request}}Copy the code
When the name is listened on, the business logic will be executed when it is updated. When we need to update the name, we just need to:
This. name = 'zhuge ';Copy the code
Computed and Watch have similarities and differences
In contrast, computed data is the calculation of complex data and is cached based on dependency. Watch listens for changes in data and performs complex business logic
Watch the attribute
Watch monitor watch monitor
Watch :{name:{handler(newVal){// business logic}}}Copy the code
The name object in Watch has an attribute: immediate
Watch :{name:{handler(newVal){// business logic}, immediate: true}}Copy the code
If immediate: true, the name object is initialized with handler. If not, the name object is not initialized with handler.
data(){ return { name: { firstName: 'ky', lastName: 'zon' } } }, watch: {name:{handler(newVal){// business logic}}}, methods: {test1(){this.name.firstName = 'hamstring '; }, test2(){ this.name = {}; }}Copy the code
Test2 is executed, and the handler method is executed. When test1 is executed, the handler method will not be executed because watch cannot listen for changes in the name attribute.
Watch :{name:{handler(newVal){// business logic}, deep: true}}Copy the code
If you want to listen for properties of the name object, you can use the deep property of the name object in Watch. When deep: true, the name object is deeply traversed, with listeners attached to each property; Added: Objects and arrays can use $set() to update data to trigger listening responses; To be continued, to continue learning