Vue3. 0 - use of composition API

I Composition API and Options API

  1. Options API options api
    (1) The advantages of the Options API are easy to learn and use, and the code has a clear writing position.
    (2) The disadvantage of Options API is that similar logic is not easy to reuse, especially in large projects.
    (3) The Options API can extract the same logic through mixins, but it is prone to naming conflicts and the source is unclear.
  2. Composition API composition API
    (1) The Composition API organizes code according to logical functions. All APIs for a function are put into one phase.
    (2) Even if the project is large and has many functions, it can quickly locate all API s of this function.
    (3) The Composition API provides code readability and maintainability.
  3. Vue3. The Composition API is recommended in 0, and the Options API is also retained.

II setup()

  1. The setup() function is a new component option that serves as the starting point for the Composition API in the component.
  2. From a lifecycle hook perspective, setup() is executed before the beforeCreate hook function.
  3. this cannot be executed in setup(). this points to undefined.
<template>
  <div>app</div>
</template>

<script>
export default {
  setup() {
    console.log("setup Yes");
  },
  beforeCreate() {
    console.log("beforeCreate Yes");
  },
};
</script>

III reactive

The reactive function accepts a normal object and returns the responsive proxy of the object.

<template>
  <div>{{ arr.title }}{{ arr.num }}</div>
  <button @click="arr.num++">modify</button>
</template>

<script>
import { reactive } from "vue";
export default {
  setup() {
    let arr = reactive({
      title: "name",
      num: 100,
    });
    return {
      arr,
    };
  },
};
</script>

IV ref

  1. The ref function accepts a value of a simple type and returns a changeable ref object with a unique attribute value.
  2. In the setup() function, the value can be accessed through the value attribute of the ref object.
  3. In the template, the ref attribute will be automatically unrolled without additional value.
  4. If ref accepts an object, it will automatically call reactive.
<template>
  <div>{{ title }}</div>
  <button @click="title = 'Name 2'">modify</button>
</template>

<script>
import {ref} from 'vue'
export default {
  setup() {
    let title = ref("Name 1");
    return {
      title,
    };
  },
};
</script>

V toRefs

  1. Convert a responsive object into an ordinary object, and each property of the ordinary object is a ref.
  2. The responsive function of reactive is given to the object, but if the object structure or expansion is given, the number will lose the ability of responsiveness.
  3. Using toRefs can ensure that every attribute expanded by the object is responsive.
<template>
  <div>{{ mame }}</div>
  <div>{{ arr.title }}{{ arr.num }}</div>
  <button @click="mame = 'ls'">modify</button>
  <button @click="arr.num++">modify</button>
</template>

<script>
import { reactive, toRefs } from "vue";
export default {
  setup() {
    let state = reactive({
      mame: "zs",
      arr: {
        title: "name",
        num: 100,
      },
    });
    return {
      ...toRefs(state),
    };
  },
};
</script>

Vi readonly

  1. Pass in an object (reactive or normal) or ref and return a read-only proxy of the original object.
  2. A read-only proxy is "deep", and any nested attributes inside the object are read-only.
  3. You can prevent objects from being modified.
<template>
  <div>{{ num }}</div>
  <button @click="num++">modify</button>
</template>

<script>
import { ref, readonly } from "vue";
export default {
  setup() {
    let num = ref(100);
    return {
      num: readonly(num),
    };
  },
};
</script>

VII computed

  1. The computed function is used to create a computed property.
  2. If a getter function is passed in, it will return a calculated property that cannot be modified.
  3. If an object with getter and setter functions is passed in, a calculated property that can be modified is returned.
<template>
  <div>Age this year:<input v-model="age" /></div>
  <div>Next year's age:<input v-model="nextAge" /></div>
  <div>Age of the next year:<input v-model="nextAge2" /></div>
</template>

<script>
import { ref, computed } from "vue";
export default {
  setup() {
    let age = ref(19);
    // Calculation properties
    // 1. Pass in a function getter and return a calculation property that cannot be modified
    let nextAge = computed(() => {
      return parseInt(age.value) + 1;
    });
    // 2. Pass in an object, including get and set, to create a calculation property that can be modified
    let nextAge2 = computed({
      get() {
        return parseInt(age.value) + 2;
      },
      //   Receive a parameter, current value
      set(value) {
        age.value = value - 2;
      },
    });
    return {
      age,
      nextAge,
      nextAge2,
    };
  },
};
</script>

VIII watch

  1. The watch function receives three parameters:
    (1) Parameter 1: data source, which can be ref or getter function.
    (2) Parameter 2: callback function.
    (3) Parameter 3: extra option, is an object. immediate and deep.
    {deep:true} deep listening
    {immediate:true} listen now
  2. watch can listen to a ref or a getter function with a return value.
  3. watch can listen to a single data source or multiple data sources.
  4. The watch function will have a return value to stop listening.
<template>
  <div>Data 1:{{ num1 }}</div>
  <button @click="num1++">Button 1</button>
  <br />
  <div>Data 2:{{ num2 }}</div>
  <button @click="num2++">Button 2</button>
  <br />
  <div>Data 3:{{ arr.title }}</div>
  <button @click="arr.title = 'Benz'">Button 3</button>
</template>

<script>
import { reactive, ref, toRefs, watch } from "vue";
export default {
  setup() {
    let state = reactive({
      num1: 100,
      arr: {
        title: "bmw",
      },
    });
    let num2 = ref(100);
    // Listen for values in a state
    watch(
      () => state.num1,
      (newValue, oldValue) => {
        console.log("Data 1 Changes", newValue, oldValue);
      }
    );
    // Monitor a single data
    watch(num2, (newValue, oldValue) => {
      console.log("Data 2 Changes", newValue, oldValue);
    });
    // Listen for objects in a state
    watch(
      () => state.arr,
      (newValue) => {
        console.log("Data 3 changes", newValue);
      },
      {
        deep: true,
        immediate: false,
      }
    );
    // Listen for multiple values
    watch(
      [() => state.arr, num2],
      ([newArr, newNum]) => {
        console.log("Data 4 Changes", newArr, newNum);
      },
      {
        deep: true,
      }
    );
    // Listen to the entire state
    watch(
      state,
      (newValue) => {
        console.log("state Changed", newValue);
      },
      { deep: true }
    );
    return {
      ...toRefs(state),
      num2,
    };
  },
};
</script>

IX Lifecycle hook function

  1. The lifecycle hook registration function provided by Vue3 can only be used synchronously during setup().
  2. Comparison between Vue3 life cycle hook function and Vue2:
    (1) Beforcreate > use setup()
    (2) Created > use setup()
    (3)beforeMount > onBeforeMount
    (4)mounted > onMounted
    (5)beforeUpdate > onBeforeUpdate
    (6)update > onUpdate
    (7)beforeDestroy> onBeforeUnmount
    (8)destroyed > onUnmounted
    (9)errorCaptured > onErrorCaptured

X Template refs

In order to obtain references to elements and component instances within the template, we can declare a ref in setup() and return it as usual.

<template>
  <div ref="hRef">Template ref</div>
</template>

<script>
import { ref, onMounted } from "vue";
export default {
  setup() {
    let hRef = ref(null);
    onMounted(() => {
      console.log(hRef.value.innerHTML);
    });
    return {
      hRef,
    };
  },
};
</script>

Xi Dependency injection (data transfer between components)

https://v3.cn.vuejs.org/guide/component-provide-inject.html

  1. Vue3 provides provide and inject dependency injection to realize the communication between components. Similar to provide and inject in Vue2.
  2. The provide and inject provided by Vue3 can be used to communicate across multi-level components.

Parent components:

<template>
  <div>This is an ancestor component:{{ num }}</div>
  <button @click="num++">modify</button>
  <br /><br />
  <Child></Child>
</template>

<script>
import { ref, provide } from "vue";
import Child from "./Child.vue";
export default {
  components: {
    Child,
  },
  setup() {
    let num = ref(100);
    // Methods called by descendant components
    let changeNum = (v) => {
      // v: the value passed by the descendant component
      num.value = v;
    };
    // Provide properties to generation level components
    provide("num", num);
    provide("changeNum", changeNum);
    return {
      num,
    };
  },
};
</script>

Subcomponents

<template>
  <div>This is a subcomponent:{{ num }}</div>
  <br /><br />
  <Grand></Grand>
</template>

<script>
import { inject } from "vue";
import Grand from "./Grand.vue";
export default {
  components: {
    Grand,
  },
  setup() {
  	// Accept the value passed from the parent component
    let num = inject("num");
    return {
      num,
    };
  },
};
</script>

Sub assembly:

<template>
  <div>This is the grandson component:{{ num }}</div>
  <button @click="fn">modify</button>
</template>

<script>
import { inject } from "vue";
export default {
  setup() {
  	// Accept the value passed from the ancestor component
    let num = inject("num");
    // Modify the data in the ancestor component
    let changeNum = inject("changeNum");
    let fn = () => {
      // Passing parameters changes the data in the ancestor component
      changeNum(200);
    };
    return {
      num,
      fn,
    };
  },
};
</script>

Keywords: Vue

Added by JakesSA on Wed, 19 Jan 2022 16:17:45 +0200