Web front-end interview high-frequency test site - Vue3.x new API (life cycle, understanding and best use of ref, toRef and toRefs)

Series Article Directory

content Reference link
JavaScript interview high-frequency test site HTML, CSS, JavaScript, ES6, AJAX, HTTP interview test site
Vue2.x interview high-frequency test site Vue2.x interview high-frequency test site


1. What are the advantages of Vue3 over Vue2?

  • better performance
  • smaller size
  • better ts support
  • better code organization
  • better logical abstraction
  • More new features

Second, the difference between Vue2 and Vue3 life cycle

App.vue parent component:

<template>
  <div>
    <life-cycles :msg="msg" v-if="flag" />
    <button @click="changeHandler">change msg</button>
    <button @click="changeFlagHandler">change flag</button>
  </div>
</template>

<script>
import LifeCycles from "./components/LifeCycles.vue";
export default {
    
    
  data() {
    
    
    return {
    
    
      msg: "hello vue3",
      flag: true,
    };
  },
  methods: {
    
    
    changeHandler() {
    
    
      this.msg = "hello vue3" + Date.now();
    },
    changeFlagHandler() {
    
    
      this.flag = !this.flag;
    },
  },
  components: {
    
     LifeCycles },
};
</script>

1. Options API life cycle

LiftCycles.vue subcomponent:

  • Vue2.x form
  • Click the button for component update and component destruction (see console output)
<template>
  <p>生命周期 {
    
    {
    
     msg }}</p>
</template>
  
<script>
export default {
    
    
  name: "LiftCycles",
  props: {
    
    
    msg: String,
  },
  beforeCreate() {
    
    
    console.log("beforeCreate");
  },
  created() {
    
    
    console.log("created");
  },
  beforeMount() {
    
    
    console.log("beforeMount");
  },
  mounted() {
    
    
    console.log("mounted");
  },
  beforeUpdate() {
    
    
    console.log("beforeUpdate");
  },
  updated() {
    
    
    console.log("updated");
  },
  beforeUnmount() {
    
    
    console.log("beforeUnmount");
  },
  unmounted() {
    
    
    console.log("unmounted");
  },
};
</script>

insert image description here


insert image description here


insert image description here


2. Composition API life cycle

  • beforeDestroy changed to beforeUnmount
  • destroyed changed to unmounted
  • Others follow the life cycle of Vue2
<template>
  <p>生命周期 {
    
    {
    
     msg }}</p>
</template>
  
<script>
import {
    
    
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";

export default {
    
    
  name: "LiftCycles",
  props: {
    
    
    msg: String,
  },
  // 等于 beforeCreate 和 created
  setup() {
    
    
    console.log("setup");

    onBeforeMount(() => {
    
    
      console.log("onBeforeMounted");
    });
    onMounted(() => {
    
    
      console.log("onMounted");
    });
    onBeforeUpdate(() => {
    
    
      console.log("onBeforeUpdate");
    });
    onUpdated(() => {
    
    
      console.log("onUpdated");
    });
    onBeforeUnmount(() => {
    
    
      console.log("onBeforeUnmount");
    });
    onUnmounted(() => {
    
    
      console.log("onUnmounted");
    });
  },
};
</script>

insert image description here


insert image description here


insert image description here


3. How to understand Composition API and Options API

Options API vs Composition API:

Please add image description

1. What does the Composition API bring?

  • better code organization
  • better logic reuse
  • better type inference

2. How to choose Composition API and Options API?

  • It is not recommended to share, it is easy to cause code confusion
  • Composition API for complex business situations
  • Options API for simple business situations

3. How to choose

  • It is not recommended to use indiscriminately, it will cause confusion
  • Small projects, simple business logic, use Options API
  • Medium and large projects with complex logic, use Composition API

4. Don’t misunderstand the Composition API

  • Composition API is a high-level skill, not a basic one
  • Composition API is designed to solve complex business logic
  • Composition API is like Hooks in React

Fourth, how to understand ref, toRef and toRefs

1、ref

  • Generate reactive data of value type
  • Can be used for reactive or template (no need for .value)
  • Use .value to modify the value
  • All ref variables should be named in the format of xxxRef as much as possible, which is easy to distinguish

Ref.vue component

  • ref is used to define reactive value types
  • reactive is used to define reactive reference types
  • The value type defined by ref can be used directly in reactive and templates (not required .value)
  • When changing the value, use.value
<template>
  <p>ref demo {
    
    {
    
     ageRef }} {
    
    {
    
     state.name }}</p>
</template>
  
<script>
import {
    
     ref, reactive } from "vue";
export default {
    
    
  name: "Ref",
  setup() {
    
    
    const ageRef = ref(21); // 值类型 响应式
    const nameRef = ref("杂货铺");

    const state = reactive({
    
    
      name: nameRef,
    });

    setTimeout(() => {
    
    
      console.log("ageRef", ageRef.value);

      ageRef.value = 18; // .value 修改值
      nameRef.value = "前端杂货铺";
    }, 1000);

    return {
    
    
      ageRef,
      state,
    };
  },
};
</script>

insert image description here


insert image description here


2. ref extension (get the dom element of the template)

RefTemplate.vue component

  • ref itself means a reference, whatever is passed to it, it points to what
  • Passing a DOM will of course point to the DOM
<template>
  <p ref="elemRef">我是一行文字</p>
</template>

<script>
import {
    
     ref, onMounted } from "vue";
export default {
    
    
  name: "RefTemplate",
  setup() {
    
    
    const elemRef = ref(null);

    onMounted(() => {
    
    
        console.log('ref template', elemRef.value.innerHTML, elemRef.value);
    })

    return {
    
    
      elemRef,
    };
  },
};
</script>

insert image description here


3、toRef

  • props (properties) for a reactive object (reactive)
  • Create a ref, with responsiveness
  • The two maintain a reference relationship

toRef.vue pairs

  • toRef(对象, "属性")Modify properties of reactive objects
  • When changing ageRef, state.age also changes
  • When changing state.age, ageRef also changes
<template>
  <p>toRef demo - {
    
    {
    
     ageRef }} - {
    
    {
    
     state.name }} - {
    
    {
    
     state.age }}</p>
</template>

<script>
import {
    
     reactive, toRef } from "@vue/reactivity";

export default {
    
    
  name: "ToRef",
  setup() {
    
    
    const state = reactive({
    
    
      age: 20,
      name: "杂货铺",
    });

    // toRef 如果用于普通对象(非响应式对象),产出的结果不具备响应式
    // const state = {
    
    
    //     age: 20,
    //     name: '杂货铺'
    // }

	// 修改响应式对象(reactive)的一个属性(age)
    const ageRef = toRef(state, "age");

    setTimeout(() => {
    
    
      state.age = 25;
    }, 1000);

    setTimeout(() => {
    
    
      ageRef.value = 30; // 用 .value 修改值
    }, 2000);

    return {
    
    
      state,
      ageRef,
    };
  },
};
</script>

insert image description here


insert image description here


insert image description here

4、toRefs

  • Convert reactive objects (reactive wrappers) to normal objects
  • Each prop of an object is a corresponding ref
  • The two maintain a reference relationship

toRefs component

  • toRefs, turn reactive objects into normal objects (still have responsiveness)
  • Each property of an object is a corresponding ref
<template>
  <p>toRefs demo {
    
    {
    
     ageRef }} {
    
    {
    
     nameRef }}</p>
</template>

<script>
import {
    
     toRefs, reactive } from "vue";
export default {
    
    
  name: "ToRefs",
  setup() {
    
    
    const state = reactive({
    
    
      age: 20,
      name: "杂货铺",
    });

    // 将响应式对象,变为普通对象
    const stateAsRefs = toRefs(state); 

    // 每个属性,都是 ref 对象
    const {
    
     age: ageRef, name: nameRef } = stateAsRefs; 

    setTimeout(() => {
    
    
      state.age = 25
    }, 1000)

    return {
    
    
      ageRef,
      nameRef,
    };
  },
};
</script>

insert image description here

Or write like this (recommended):

  • Return this ordinary object directly
  • Note that the template content has also changed at this time, directly write the properties in the object
<template>
  <p>toRefs demo {
    
    {
    
     name }} {
    
    {
    
     age }}</p>
</template>

<script>
import {
    
     toRefs, reactive } from "vue";
export default {
    
    
  name: "ToRefs",
  setup() {
    
    
    const state = reactive({
    
    
      age: 20,
      name: "杂货铺",
    });

    // 将响应式对象,变为普通对象
    const stateAsRefs = toRefs(state); 

	setTimeout(() => {
    
    
      state.age = 25
    }, 1000)
    
    return stateAsRefs
  },
};
</script>

insert image description here

insert image description here

5. Best use of ref, toRef and toRefs

  • Use reactive as object responsiveness, and use ref as value type responsiveness
  • Return toRefs(state) in setup, or toRefs(state, 'xxx')
  • ref variables are named using xxxRef
  • Use toRefs when a composite function returns a reactive object

xxx.js file

  • Defining functions and reactive objects
  • Convert to ref on return
import {
    
     toRefs, reactive } from "vue"

function useFeatureX() {
    
    
    const state = reactive({
    
    
      x: 1,
      y: 2
    })
  
    // 逻辑运行状态,省略 N 行
      
    // 返回时转换为 ref
    return toRefs(state)
}

export default useFeatureX

xxx.vue components

  • You can directly write the properties of the object when you use it
export default {
    
    
  setup() {
    
    
    // 可以在不是去响应式的情况下破坏结构
    const {
    
     x, y } = useFeatureX()

    return {
    
    
      x,
      y
    }
  } 
}

不积跬步无以至千里 不积小流无以成江海

If this article is of any help to you, please feel free toTriple + FollowA wave of support, high-quality and good articles, are being produced...

Guess you like

Origin blog.csdn.net/qq_45902692/article/details/126630532