VUE 3 0 Learning Exploration Starter Series Vue3 x Lifecycle and Composition API Core Syntax Underst

Mondo Technology Updated on 2024-03-02

beforecreate, which is called after the instance is initialized, before the Data Observer and Event Watcher event configurations. created, which is called immediately after the instance is created. In this step, the instance has been configured with the following parameters: data observer, properties and methods operation, watch event event. However, the mount phase has not yet begun, and the $el property is not yet available. beforemount, which is called before the mount starts: The relevant render function is called for the first time. mounted, which is called after the instance is mountedelis newly createdvm.$elreplaced. If the root instance is mounted on an element within a document, mounted is calledvm.$elAlso within the documentation. beforeupdate, which is called when the data is updated, occurs before the virtual DOM is patched. This is a good place to access an existing DOM before updating, such as manually removing added events***updated, the hook is called after the virtual DOM is re-rendered and patched due to data changes. activated, which is activated by a keep-alive cached component. deactivated, which is called when a component cached by keep-alive is deactivated. beforedestroybefore the instance is destroyed. At this step, the instance is still fully available. destroyedand call the instance after it is terminated. After the hook is called, all the instructions corresponding to the vue instance are unbound, all events*** are removed, and all child instances are destroyed. errorcaptured, which is called when an error from a descendant component is caught. Reference: cnvuejs.The ORG v2 API options -...Reference: cnvuejs.org/v2/guide/in…is replaced

beforecreate ->setup()created ->setup()Rename

beforemount ->onbeforemountmounted ->onmountedbeforeupdate ->onbeforeupdateupdated ->onupdatedbeforedestroy ->onbeforeunmountdestroyed ->onunmountederrorcaptured ->onerrorcapturedNew

The following 2 new ones are added for easy debuggingdebug**Hook:

onrendertrackedonrendertriggered: vue-composition-api-rfcnetlify.com/api.html#li…Special Instructions

Thanks to vue3X is VUE2 compatiblex, so in order to guarantee vue2The syntax for x works fine in vue3x, most of vue2The ** function of x is still retained. For example: thoughbeforecreatecreatedbesetup()function instead, that is to say in vue3xsetup(), instead of the old API, but if you want to use it, it will also work as normal.

However, the following 2 lifecycle hook functions were renamed in vue3There will be no more in xbeforedestroywithdestroyed

beforedestroy ->onbeforeunmountdestroyed ->onunmountedAlso, if vue3If X is released on schedule in Q2, you must be aware that you are using vue2 in a mixed mannerx and vue3X syntax, pay special attention to the order of execution of the ** functions of these two sets of APIs.

If you guys read my last post on vue 30 Learning to Explore Starter Series - Wondering if to upgrade to VUE30?How do I upgrade? (5), I said when vue3I'll probably use it first after X officially realeasevue2.x + composition api, use it again when you are donevue3.xBuild a new foundation. That's one of my main concerns today once I use itvue2.x + composition apiAfter entering the transition period, when I use it againvue3.xIf you build a new framework, will the previous basic components still be used?

First, test the order in which the lifecycle functions are executed.

In the following example, in vue2X introduces the compatibility package Composition API, and then vue2x and vue3x's lifecycle functions are mixed.

Execution Result:

1. beforecreate2. setup3. data4. created5. beforemount6. onbeforemount7. mounted8. onmounted9. beforeupdate10. onbeforeupdate11. updated12. onupdated13. beforedestroy14. onbeforeunmount15. destroyed16. onunmounted
Conclusion

Invue2.xis introduced in the form of patchescomposition api, carried outvue2.xwithvue3.xWhen the ** function is mixed:vue2.The ** function of x will be executed relatively first, such as:mountedPriority is given toonmounted

The following uses vue3 directlyX syntax to see if it's compatible with vue2x case, the order in which the lifecycle functions are mixed.

Execution Result:

1. beforecreate2. data3. created4. onrendertracked5. onrendertracked6. onbeforemount7. beforemount8. onmounted9. mounted10. onrendertriggered11. onrendertracked12. onrendertracked13. onbeforeupdate14. beforeupdate15. onupdated16. updated17. onbeforeunmount18. beforeunmount19. onunmounted20. unmounted
Conclusion

Invue3.x, in order to be compatiblevue2.xAll of the old lifecycle functions are preserved (exceptbeforedestroywithdestroyed), when lifecycles are mixed:vue3.The lifecycle of X takes precedence over Vue2x, such as:onmountedthanmountedExecute first.

In summary: invue2.xis introduced in the form of patchescomposition api, carried outvue2.xwithvue3.xWhen the ** function is mixed:vue2.The ** function of x will be executed relatively first, such as:mountedPriority is given toonmounted。Invue3.x, in order to be compatiblevue2.xAll of the old lifecycle functions are preserved (exceptbeforedestroywithdestroyed)。), when lifecycles are mixed:vue3.The lifecycle of X takes precedence over Vue2x, such as:onmountedthanmountedExecute first. Through the comparison, it can be concluded that:When your major version is which one is and whose hooks are compatriotically prioritized when lifecycles are mixed.

So, it's going to be a bit of a pit here! In order to give less unnecessary trouble later, if everyone is invue2.xis introduced in the form of patchescomposition apiWhen using, it is recommended:

Don't mix vue2x and vue3The life cycle of x。Either you continue to use vue2x, or use vue3x, so that's fine. In the case of Principle 1,It is recommended that the source code be separated from the old and new versions from the project or directory。Easy to upgrade later or be introduced to vue3x When used, there is a more targeted compatibility test. Most of the following content is referred to the official VueComposition APIsetupis the core of the composition API, and arguably the whole of vue3The core of x.

setupThat's what will be vue2xbeforecreatewithcreatedInstead, to onesetupThe form of functions can be flexibly organized**. setupYou can also return data or template, which is equivalent to puttingdatawithrenderIt was also replaced! WhysetupFlexible? Because in this function, each lifecycle can be a function, executed in it, programmed in a functional way.

Let's take a look at a few of its core features:

1 returns a set of data to the template

2 Use JSX syntax

3 typescript type

interface data interface setupcontext function setup( props: data, context: setupcontext): data
4 Parameters

It should be noted that in:setupfunction, canceledthis!There are two reasons:

Due tosetupIt is an entrance function, which is essentially function-oriented programming, andthisIt's an embodiment of object orientation! In the world of fully function-based programming, thisthisIt's hard to get up to the same level as vue2x the effect of the implementation of the options mechanism based on the idea of oop.

It is also based on functional programming, so if you add this, it will be difficult for novices to understand this, and it will be even more confusing at this time. , such as:

setup()
Canceledthis, and insteadsetupAdded 2 parameters:

props, component parameter context, context information

setup(props, context)
You may wonder, are these 2 parameters enough? That's enough. You're in vue2x times,thisCan't you just get some data, props, computed, methods, etc.?

Actually, these two parameters are introduced externally, and there is no way to bring them into the initialization function. On top of that, all the data that you can get with this on your component is now defined in the setup, like a local variable, so why do you want this?

, such as:

setup(props, context) ) compute function const plusone = computed(()=> count.value + 1) methods method const testmethod = ()=> return to template return }
Everything is insetup, are equivalent to becomingLocal variablesNow, you still want itthisWhy?

Of course, if you're going to talk about vue2x and vue3x Mix! That's awkward, use this in the future, and you can't use it in the future, and you'll be confused yourself, so here's the suggestion:Although vue3X is compatible with VUE2x syntax, but it is not recommended to mix and match their own syntax!

bereactivemethod after wrappingObjectIt becomes a ** object, equivalent to vue2xvue.observable()。It is also possible to realize the two-way binding between the page and the data.

The method of this wrapping is:deep, which is valid for all nested attributes.

Note:General ConventionsreactiveThe argument is an object, and the one mentioned belowrefThe parameter is a basic element. But if it's okay to do it the other way around,reactiveIn fact, it can be any value, such as:reactive(123)It can also be turned into a ** element, which can achieve two-way binding.

, such as:

Page display results:

As you can see, when the properties of common objects are updated, the page is not updated synchronously. Only ** objects can be bound in both directions.

berefmethod after wrappingelementIt becomes a ** object. Generally speaking, the element parameters here refer to:Basic elementsOr call it thatinner value, such as: number, string, boolean, null, undefied, etc., object is generally not usedref, and instead use the one abovereactive

That is to sayrefGenerally applicable to an element; WhilereactiveApplies to one object.

refIt's the equivalent of converting a single element into onereactiveobject, the default key-value name of the object is:value

, such as:

setup()
berefThe wrapped element becomes a ** object, and the effect is equivalent to:

setup()
Because it has become a ** object, it is needed when taking the value.value

setup()
In additionrefThe results are intemplateIt will be automatically turned on when in useunwrap, no need to add more.value

Here are some of the basic elementsrefResults:

setup() value) // output: )plusone.value = 1console.log(count.value) // 0console.log(plusone.value) // 100
plusone.value = 1It is equivalent to assigning a value to the calculated object, which will be triggeredsetfunction, thuscountThe value has been modified.

usereadonlyfunction, you can put itNormal object objectreactive objectref objectReturns a read-only object.

The returned readonly object will have a warning in the console once it is modified. The program will still run as usual without errors.

const original = reactive()const copy = readonly(original)watcheffect(()=> ) This triggers WatchEffectOriginalCount++ doesn't trigger the watcheffect above here because it's readonly. copy.count++ // warning!
There are also APIs such as:watchwatcheffectWait, I won't talk about it here, the above are some of the more important syntax, I hope it can help you.

Related Pages