“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Create using vue-CLI

Create the project using Webpack VUe-CLI

  1. Vue-v must be higher than 4.5.0
  2. NPM install -g@vue /cli Installs or upgrades the CLI
  3. Vue create Project name
  4. NPM Run Server starts

Create projects using the latest Vite

Vite’s advantages:

  • Development environment, no packaging, can be quickly cold start
  • Lightweight fast thermal overload
  • Compile as needed, without waiting for the entire application to compile

Create using Vite:

  1. NPM i-g create-viet-app global installation
  2. NPM init vite-app Project name
  3. NPM install depend on
  4. NPM run dev starts

Common Composition API

Composition–> Composition API

Official document address: v3.cn.vuejs.org/

1. Setup function

Setup “Performer’s stage”

Understanding: A new configuration in Vue3.0 with a value of a function.

  • Everything used in a component: data, methods, and so on, is configured in Setup.

  • The setup function returns two values:

    1. If the object is returned, the attributes and methods in the object can be used directly in the template. (key)Copy the code
    2. If a render function is returned: then you can customize the render content.Copy the code
  • Note:

    1. Do not mix with vue2.0 configurations

    Vue2. X configuration (Data, Methos, ComputeHD..) You can access setup properties, methods,!! The configuration data, methos, computehd in Vue2. X cannot be accessed in setup.

    2. If the same name exists, setup takes precedence

    Setup cannot be an async function because the return value is not a return object, but a promise. The template does not see the property value in the return object. It is also possible to return a Promise column later, but to work with asynchronous components

    2. Ref function (use of basic data)

  • Function: REF acts as the responsive core of 3.0

  • Const XXX = ref{initValue}

    • Create a reference object (ref object) that contains responsive data.
    • JS data: xxx.value
    • {{name}}
  • Remark:

    • The data received can be either a primitive type or an object type

    • The basic types of data: The response is still completed by the Get and set of Object and defieProperty()

    • Object type data: Internal “recourse” to a new function in Vue3.0, reactive (originally a Proxy)

    • He encapsulates ES6 proxies into reactive functions and continues to use them.

    Function reactive (object type)

  • Function: Defines a reactive data type for an object type (do not use it for basic data types, use ref instead)

  • Syntax: const Proxy object, reactive(source object), receives an object (or array) and returns a Proxy object (a live-column object)

  • Reactive defines reactive data as “deep”

  • Internal Based on ES6 Proxy, through the Proxy object to operate the internal data of the source object.

4. Responsivity principle in Vue3.0

Responsiveness of VUe2.0:
  • Implementation principle:

    • Object type: Intercepts reading and modifying attributes with Object.defineProperty() (data hijacking)
    • Array type: Intercepts by overriding a series of methods that update an array, (wrapping array change methods)
    • Object.defineProperty(data, 'count',{
          get() {},
          set() {}
      })
      Copy the code
  • Existing problems:

    • Add attribute, delete attribute, interface will not update.
    • Modify the array directly by subscript, the interface does not automatically update.
Responsivity of VUe3.0:
  • Implementation principle:

    • Through Prxoy (proxy) : Intercepts the change of any property in the object, including: property worth reading and writing, property to add, property to delete, etc
    • Through Refiect: Operate on properties of the proxied object.
    • MDN Proxy Reflect

Contrast Reactive and Red

From the point of view of defined data:

  • Ref is used to define basic type data
  • Reactive is used to define object (or array) types.
  • Note: Ref can also be used to define object (or array) type data, which is automatically internally converted to a proxy object by Reactive

From the perspective of principle:

  • Ref implements responsiveness through get and set of Object.definProperty() (data hijacking)
  • Reactive implements data hijacking by using proxies, and reflects manipulates data inside the source object.

From the perspective of use:

  • Data defined by ref: Operation data requires. Value, which is not required when reading data directly from the template
  • Data defined by Reactive: operating data and reading data: value is not required

Two points to note about SETUP

  • When setup executes:

    • Execute once before beforeCreate, this is undefined
  • Parameters to setup:

    • Props: objects that contain properties passed from outside the component but not declared in the props configuration, equivalent to this.$attrs

    • Context: context object

      • Attrs: The value is an object containing: properties passed from outside the component, but not declared in the props configuration, equivalent to this.$attrs
      • Slots: The received slot content is equivalent to this.$slots.
      • Emit: A function that distributes custom events, equivalent to this.$emit

7. Calculate properties and monitor

1. Computed functions

  • This function is consistent with computed configuration in vue2. x
  • Writing:
Import {reactive, computed} from 'vue' setup() {let person = reactive({firstName: 'xu ', lastName: 'name', }) // Compute attributes 3.0 (not counting computed attributes modified) Read-only /* person.funllnmae = computed(() => {return person.firstName + person.lastName })*/ // Full notation 2 considers reading and writing person.funllnmae = computed({get(){return person.firstname +'-'+ person.lastname}, set(value){ const nameArr = value.split('-') person.firstName = nameArr[0] person.lastName = nameArr[1] } }) return { person } }Copy the code

2. Watch function

  • It has the same configuration function as watch in Vue2. X

  • Two small pits:

    • When monitoring reactive data defined by Reactive: oldValue (before update) cannot be obtained correctly, and deep listening is enabled in front (deep configuration fails)
    • When monitoring a specific genus of reactive data defined by Reactive: the deep configuration is valid
Watch 3.0 can pass three parameters (the first is the data source, the second is the result of listening, and the third is the configuration (deep listening, immediate listening)). /* watch(sum, (newValue, oldValue) => {console.log('sum changed ', newValue, oldValue)}, {immediate: true})*/ //deep: True Currently do not know whether there are any questions // Case 2: /* watch([sum, MSG], (newValue, oldValue) => {console.log('sum or MSG changed ', newValue, OldValue)})*/ // check the value of an oldValue specified by reactive. You can avoid this by taking the object in Reactive out and giving it to the REF. Reactive is called when ref detects that you are an object. Reactive is called when ref detects that you are an object. */ /* watch(person, (newValue, oldValue) => {console.log('person value changed ', newValue, /* watch(()=>person.age, (newValue,); OldValue) => {console.log('person value changed ', newValue, /* Watch ([()=>person.age,()=>person.name], (newValue, OldValue) => {console.log('person value changed ', newValue, OldValue)})*/ / deep /* watch([()=>person.obj,()=>person.name], (newValue, OldValue) => {console.log('person value changed ', newValue, OldValue)},{deep:true}) {deep:true}) {deep:true} In the case of objects, calling reactive produces proxy functions in value, so when you want to listen, write personref. value or enable deep listening: Value watch(MSG. Value, () => {}) Watch (personref. value, (qian, hou) => {console.log('person value changed ', Qian, hou)})Copy the code

3. WatchEffect function

  • Watch routine: Specify both monitoring properties and monitoring callbacks.

  • The watchEffect formula is this: instead of specifying which property to watch, watch which property is used in the monitored callback function

  • WatchEffect kind of wants computed:

    • But for computed values (the return value of the callback function), you have to write the return value
    • WatchEffect focuses more on the procedure (the body of the callback function), so it doesn’t write the return value

8. Life cycle

Vue3.0 can continue to use the lifecycle functions in vue2.x, but two of them have been renamed (the destroyed lifecycle becomes unmounted)

  • BeforeDestroy ====> beforeUnmount (unmount)

  • destroyed =======> unmounted

  • Vue3.0 also provides a composite API (which needs to be introduced), which corresponds to vue2.x as follows

  • BeforeCreate ====> setup

  • Created ====> setup

  • BeforeMount ===> onbeforeMount (Bind)

  • mounted =======>onmounted

  • BeforeUpdate ===>onbeforeUpdate (modify)

  • updated ========>onupdated

  • BeforeUnmount ====> onbeforeUnmount (unmount)

  • unmounted =======> onunmounted

9. Custom hook functions (emphasis)

  • What is a hook? The essence is a function that encapsulates the Composition API used in setup functions.
  • Similar to mixins in Vue2.0.
  • Advantages of custom hooks: Reusing code makes the logic in setup much clearer and easier to understand

10. ToRef (key point)

  • Creates a ref object with value pointing to an attribute in another object
  • Const name = toRef(person, ‘name’)
  • Application: When a property of a reactive object is individually provided for external use
  • Extension: toRefs has the same functionality as toRef, but can batch create multiple REF objects, syntax: toRefs (person)

In the next post, we will continue to update other apis and new writing methods! Give it a thumbs up if you like