directory

  1. Limitations of Vue2
  2. Vue2 – Solution for reusing code across components (bad)
  3. Code reuse approach PK
  4. How can I solve a problem using the CompositionAPI
  5. Code level differences: such as the implementation of data listening
  6. .

1. Limitations of Vue2

  • Poor readability due to component logic bloat
  • Code cannot be reused across components
  • Vue2 has limited support for TS

In traditional OptionsAPI we need to split the logic into the following six parts

OptionsAPI

-   components
-   props
-   data
-   computed
-   methods
-   lifecycle methods
Copy the code

This will cause us to edit a logic and have to repeatedly jump through the code

Vue2 – Solution for reusing code across components (bad)

  1. Mixin (problematic)
  2. Scope slot slot (many drawbacks)
  3. Higher-order components (too complex)

Third, code reuse method PK

There are roughly four options for reusing code across components in Vue2.

3.1) Mixin

Code mixing is actually a hybrid of design patterns, and its drawbacks are obvious.

You can think of it as multiple inheritance, which is basically how does one person have two fathers

❌ Can’t avoid attribute name conflicts – long nose is whatever

❌ Inheritance relationship is not clear

3.2) Mixin Factory – Mixin Factory

✅ code reuse is convenient

✅ Inheritance relationship cleaning

3.3) ScopeSlots – ScopeSlots

  • ❌ is not very readable
  • ❌ Complex configuration – You need to perform the configuration in the template
  • ❌ Low performance – Each slot equals one instance

3.4) CompositionApi – Composite API

  • ✅ code quantity is small
  • ✅ introduces no new syntax and is simply a function
  • ✅ Extremely flexible
  • ✅ tool syntax hint friendly – because it is a simple function so easy to implement syntax hint, automatic compensation

How to Solve a Problem using Composition API

The best solution is to aggregate the logic for good code readability.

This is what our Position API syntax can do. CompositionAPI is a completely optional syntax that does not conflict with the original OptionAPI. It allows us to group together code that does the same thing without having to be scattered all over the optionsAPI.

LifecycleHooks – LifecycleHooks

Vue2 Vue3
beforeCreate ❌ setup (alternative)
created ❌ setup (alternative)
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured
🎉 onRenderTracked
🎉 onRenderTriggered

Six, the code level difference: for example, the implementation of data monitoring mode

reference

Check out the link below for more Vue2 VS Vue3

  • Vue3 official tutorials are synchronized with tutorial videos

conclusion

  • Vue2 to 3 code dispersion -> code aggregation
  • Reuse code across components through Composition