Describes the basic uses of computed data

Basic Usage 1
    new Vue({
        data () {
            return {
                num: 0}}computed: {
            result () {
                return this.num++
            }
        }
    })
Copy the code
Basic Usage 2. Use with vuEX
    // vuex store.js
    
    const store = new Vuex.Store({
        state: {
            storeNum: 2}})// Vue component xx.vue
    <template>
        <div>{{result}}</div>
    </template>
    <script>
    import { mapState } from 'vuex'
    export default {
        data () {
            return {
                dataNum: 0}},computed: mapState({
            result: state= > state.storeNum + this.dataNum
        })
    }
    </script>
Copy the code
Use with vuex, and use mapState, and want to write some other properties
    import { mapState } from 'vuex'
    export default {
        data () {
            return {
                num: 0}},computed: {
            ...mapState({
                storeNum: state= > state.storeNum
            }),
            result() {
                return this.num + 3 + this.storeNum
            }
        }
    }
Copy the code
To modify the value of a computed property, you need to add setters for computed properties

The calculated properties of vue are based on the properties in data, that is, the values of the properties in data can be used in the calculated properties. If the calculated properties use the property dataNum in Data, the values of the calculated properties will also change if the value of dataNum is modified. Do not modify the computed properties directly, the computed properties view will not change.

    export default {
        data () {
            return {
                dataNum: 0}},computed: {
            result: {
                get () {
                    return this.dataNum + 3
                },
                set (newValue) {
                    this.dataNum = newValue
                }
            }
        }
    }
Copy the code

How does Vue initialize computed, and what does Vue do when using computed properties?

Before initializing computed, Vue initialized props, Methods, and data. So for computed, we can use properties in props, methods, and data. Let’s look at the initialization process for computed.

    // the source location is instance/ state.js
    const computedWacthers = {lazy: true}
    export function initState (vm) {
         const opts = vm.$options
         ...
         if (opts.computed) initComputed(vm, opts.computed) // Computed: {XXX: fn}. }function initComputed (vm, computed) {
        const watchers = vm._computedWatchers = object.create(null) // The watcher for each attribute is stored
        for (const key in computed) {
           // Iterate over computed properties
           const userDef = computed[key] // Get each item in computed
           const getter = typeof userDef === 'function' ? userDef : userDef.get
           // Check here whether everything in computed is a function or whether there is a get method. If not, throw an error
           watchers[key] = new Watcher(
               vm, 
               getter || noop, 
               noop, 
               computedWatchers
               ) // Add a response for each item of the calculated property
           // The calculated properties defined by the component are already defined on the component prototype, we only need to define the calculated properties defined at instantiation here.
           definedComputed(vm, key, userDef)
       }
    }
    
    function definedComputed (vm, key, userDef) {
        // Server rendering is not considered
        if (typeof userDef === 'function') {
            sharedPropertyDefinition.get = createComputedGetter
            sharedPropertyDefinition.set = noop
        } else {
            sharedPropertyDefinition.get = userDef.get ? createComputedGetter(key) : noop
            sharedPropertyDefinition.set = userDef.set || noop
        }
        // If you set get and do not set set, and then modify the calculation properties, an error will be reported.
        Object.defineProperty(vm, key, sharedPropertyDefinition)
    }
Copy the code

So far we have seen the initialization process for computed, traversing the attributes in computed, setting the corresponding Watcher instance for each attribute, and then defining the calculated attributes for Vue instantiation. After the thing.

What does VUE do for us when using computed attributes?

When computed is initialized, a corresponding Watcher instance is set for each attribute in computed. When we use a property value in a calculated property, we call the computedGetter method, which is not mentioned above and is actually the return value of the createComputedGetter method in the definedComputed method. Now let’s see what vUE does for us when we use values in computed properties.

    function createComputedGetter (key) {
        return function computedGetter () {
            const watcher = this._computedWatchers && this._computedWatchers[key]
            _computedWatchers defined above when computed was initialized is now used
            if (watcher) {
                if (watcher.dirty) {
                    watcher.evaluate() Get () and set watcher.dirty = false. Set dirty to false
                }
                if (Dep.target) {
                    watcher.depend() // Soga, where he collects dependencies for each key.
                }
                return watcher.value // Return the value of the call to watcher.get(), which is the function set in your calculated property.}}}Copy the code

When we initialize the new Watcher, we call the watcher get method and assign dep. target to the current watcher instance. Then call watcher.depend() to collect the dependency for this calculated property.