preface

For front-end engineers using the VUE technology stack, it is common to be asked in interviews what is the difference between Watch and computed, and whether they know anything about computed implementation. So let’s take a look at how computed works and how caching works.

To read this article, you need to understand the response principle of vue2.X

1. Basic use in VUE project

We often use this in components in VUE projects

<template> <div class="container"> {{ name }} </div> </template> <script> export default { data () { return { firstname:  'yang', lastname: 'yusi' }; }, computed: { name() { return this.firstname + this.lastname; } }, } </script>Copy the code

As we know, when the component is initialized, the initState method is first called to add a response to the data defined in props, data, computed, and watch, and when the data changes, the view is notified to update it (see the VUE responsiveness principle).

When firstName or lastName changes, the value of name is also recalculated. And how name gets cached values when firstName and lastName values do not change.

As you can see from the figure above, initState initializes the computed property of the component, namely initComputed methods.

After executing the defineComputed method, our userDef === ‘function’ is judged by the condition, so the createComputedGetter(‘name’) method is executed.

Why is lazy true

It’s manually set

Here is Watcher’s Evaluate method

Triggers watcher’s get method, which executes

function () {
    this.firstname + this.lastname;
}
Copy the code

Reading the values of firstName and lastName fires their getter methods and collects the watcher values into their Dep dependency lists, so when their values change, it fires the setter methods, Trigger the update method for water,

After setting lazy to true, dirty is set to true, the value of name is updated, and the view is triggered to update. This is how computed works.

One question remains: how does computed cache work? When we first get the value of name, we set dirty = true. When we read the value of name again, we will read the value of Watcher directly, which is the value of the initialization.

If there is something wrong, welcome comments pointed out ~~