What are the advantages of Vue3 over Vue2

Better performance, smaller size, better TS support, better code organization, better logic decoupling, more new featuresCopy the code

Vue3 life cycle

1Options Api life cycle beforeDestory was changed to beforeUnmount, deStoryed was changed to unmounted, other life cycles use Vue22, Composition Api lifecycle SetUp (equal to beforeCreate and Created), onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmountedCopy the code

Composition Api vs. Options Api

Composition Api is for large complex applications. It is designed to solve complex business logic

1Better code organization2, better logic reuse3Better type derivationCopy the code

It is not recommended to use the two together, which will cause confusion and small projects. For simple logic, use the Options Api, for medium and large projects, and use the Composition Api for complex logic

How to understand ref toref and toRefs

The reason for using ref

1, return value type, the response will be lost2SetUp, compoted, and composition functions may all return value types3If Vue does not define ref, users will create their own ref, which will become more chaoticCopy the code

The reason for using. Value

1Ref is an object, value stores a value2And is implemented through the. Value property of get and set2Value is required in other casesCopy the code

Reasons for using toRef toRefs

1Original intention: Disperse/diffuse object data without losing the appropriate situation2Premise: For reactive objects (non-common objects encapsulated by Reactive)3Note: do not create reactive, but continue reactiveCopy the code

Ref: generates a reactive value type, which can be used in templates and reactive, and modifies data through. Value

ToRef: A prop for a reactive object that, if used on a normal object, does not produce a reactive result

ToRefs: A reactive object is wrapper into a regular object, and each prop of the object is a ref. The reference relationship between the two is maintained. By virtue of the fact that regular objects can be deconstructed, the reactive object deconstruction will not be reactive

Best use:

1, reactive for object response and ref for value type response2SetUp tiRefs(state), or toRef(state,'XXX')
3XxxRef is used to name the variables of and ref4The synthesized function returns a reactive object, using toRefsCopy the code

What are the important features that Vue3 has upgraded

1, createApp2, emits attribute3, multi-event processing4Fragment (remove template single node limit)5Sync Set the parameter to v-model6And how asynchronous components are referencedimport {createApp, defineAsyncComponent } from 'vue'
createApp({
    components: {
        AsyncCompontne: defineAsyncComponent(() = >  import('XXXXXXXXX.vue'))}})7And remove the filter8, Teleport (mount an element below an element) < Teleport tpo="body">
    <div></div>
</teleport>
9</Supense> </Supense>10Composotion Api Reactive, Ref-related, Readonly, Watch and watchEffect, Setup, lifecycle hook functionsCopy the code

Composition API for logic reuse

1And extract logic to a function2. The function naming convention is useXXX format3Use this function in setupCopy the code

The Proxy function

const proxyData = new Proxy(data, {
    get(target, key, receiver) {
        // Only handle the (non-prototype) attributes themselves
        const ownKeys = Reflect.ownKeys(target)
        if (ownKeys.includes(key)) {
        }
        const result = Reflect.get(target, key, receiver)
        return result
    },
    set(target, key,val, receiver) {
        // Duplicate data is not processed
        const oldvalue = target[key]
        if (val === oldValue) {
            return true
        }
        const result = Reflect.set(target, key, vakl, receiver)
        return result
    },
    deleteProperty(target, key) {
        const result = Reflect.deleteProperty(target, key)
        return result
    }
})
Copy the code

Reflect function

1, andProxyAbility one to one correspondence2, normalization, standardization, functionalization3, replace theObjectThe utility functions aboveCopy the code

Vue3 responsive

const data = {
    name: 'XXX'.info: {
        address: 'XXX'}}const proxyData = reactive(data)

function reactive(target = {}) {
    if (typeoftarget ! = ='object' || target == null) {
        return target
    }
    const proxyConf = {
        get(target, key, receiver) {
            // Only handle the (non-prototype) attributes themselves
            const ownKeys = Reflect.ownKeys(target)
            if (ownKeys.includes(key)) {
                //
            }
            const result = Reflect.get(target, key, receiver)
            // Deep monitor
            // How to improve performance, deep listening at get
            return reactive(result)
        },
        set(target, key,val, receiver) {
            // Duplicate data is not processed
            const oldvalue = target[key]
            if (val === oldValue) {
                return true
            }
            // Determine whether to add attributes
            const ownKeys = Reflect.ownKeys(target)
            if (ownKeys.includes(key)) {
            } else{}const result = Reflect.set(target, key, vakl, receiver)
            return result
        },
        deleteProperty(target, key) {
            const result = Reflect.deleteProperty(target, key)
            return result
        }
    }
    // Generate a proxy object
    const observed = new Proxy(target, proxyConf)
    return observed
}

Copy the code
1, depth monitoring, better performance2, can listen to delete/add attributes2, can listen for array changesCopy the code

V-model parameter (two-way binding effect)

Similar vue2. Async

The difference between Watch and watchEffect

1, both can monitor data attribute changes2Watch needs to specify which attribute to listen on3WatchEffect automatically listens for changes based on its propertiesCopy the code
// Value type ref
watch(XXX, (newVal, oldVal) = > {
    // Listen logic
}, 
/ / {
// immediate: true // Listens before initialization, optional
// }
)
// A responsive object
watch(
    // Determine which property of the object to listen on
    () = > XXX.xxx,
    (newVal, oldVal) = >{},/ / configuration items
    {
        immediate: true.// Listen before initialization, optional
        // deep: true // deep listening})// Listen for the dependency used in the function
watchEffect(() = > {
    // It must be initialized once
})
Copy the code

How do I get a component instance in Setup

1, is missing from setup and other Composition apisthis
2To get the current instance, run getCurrentInstance3, available if using the Options APIthis
Copy the code

Why is Vue3 faster than Vue2

1,Proxyresponsive2When compiling the PatchFlag template, dynamic nodes are marked and divided into different types. For example, when the TEXT PROPS DIff algorithm is used, static nodes and different types of dynamic nodes can be distinguished3hoistStatic promote the definition of static nodes to the parent scope and cache multiple adjacent static nodes, which will change the combined typical optimization strategy of taking space for time4, cacheHandler Cache events5SSR optimized static node output directly, bypassing vDOM dynamic node, or need dynamic rendering6, tree-shaking compile time, different apis are introduced for different scenariosCopy the code

Vite

1, a full segment packaging tool, Vue author initiated project2, with the influence of Vue, fast development and competition with Webpack3Advantages: Development environment without packaging, fast startupCopy the code

Cause of fast startup

1, the development environment uses ES Module, no packaging, very fast

2. Production environments using rollup are not much faster

Composition API vs. React Hooks

1The former setup is called only once, while the latter function is called multiple times2The former does not require useMemo useCallback because setup is called only once3The former requires no need to call the book on demand, while the latter requires that hooks be in the same order4And Reactive + ref is more difficult to understand than useStateCopy the code