Introduction: Vue3.0 has been released for a period of time, and some companies began to use Vue3.0+TS+Vite for project development. The interview for the Vue position is a must. I have collected some common features of Vue3.0 that I hope will be helpful to developers learning about Vue3.0 or preparing for an interview

Synthesis of apis

Composition API is a new feature provided by Vue3.0, which makes use of setUp and provides some responsive APIS, life cycle, etc., so that Vue developers have a new development mode, solves the problem of high cost of maintaining large components in the past, and at the same time more standardized the project flow of Vue development

1.setUp

<template> <div> <p>{{ num }}</p> <p>{{ obj }}</p> </div> </template> <script lange="ts"> import { reactive, ref } from "@vue/reactivity"; export default { setup(props,context) { const num = ref(0); const obj = reactive({ name: "xxx", age: 10, }); onBeforeMount(() => { console.log("onBeforeMount"); }); onMounted(() => { console.log("onMounted"); }); return { num, obj, }; }}; </script>Copy the code
  • In Vue3.0, setup is used as an entry point for data and functions and other configuration items, replacing the previous configuration encoding patterns of data, Method, and life cycle
  • The life cycle of setup is before the beforeCreate, so this in setup is set to undefined by the Vue designer, and we can’t use this for data calls and function calls like before
  • The return value of the setup function is that we can use data sources on the page and in methods (in conjunction with Vue2.0), where REF and Reactive are the responsive apis,onBeforeMount and onMounted are the lifecycle functions provided, as opposed to Vue2.0’s BeforeMount and Mounted Indicates the same meaning, but the onXX life cycle precedes the XX life cycle. Only variables after reactive processing have the bidirectional binding update feature.
  • The setup function is not required to use the async await form in most cases, as forcing it will result in the failure to call the returned response data
  • The setup function takes two arguments. The first argument is props, which has the same meaning as Vue2.0’s props and represents the properties received by the current component. The second argument is context, which is actually an object containing attributes such as attrs(set of properties not received by props),emit(used to trigger custom events registered with the component), and expose(exposed methods or return values that invoke child components — to be explored).
  • The two parameters of setup are responsive, but cannot be deconstructed without losing their responsiveness. The context parameter can be structured, and the three commonly used properties are all up-to-date values
  • Setup can also return a render function, which is used in the same way as Vue2.0 provides.
  • Provide and Inject can also be used in setup to transfer properties between grandparents and grandchildren, which is also non-responsive.
import { h, ref, reactive } from "vue"; export default { setup() { const readersNumber = ref(0); const book = reactive({ title: "Vue 3 Guide" }); Return () => h("div", [readersnumber.value, book.title]); }};Copy the code

Ref and Reactive API

Ref and Reactive are both used to add reactive apis to data. The difference is that we are encouraged to use REF to define responses for basic data types, while Reactive defines responses for reference data types because of their underlying processing mechanisms

  • The underlying source implementation of ref is still Object.defineProperty. Its return value is an Object processed by the function. The Object contains a value property that gives us the original value passed in, and the modified value also depends on this property
const num = ref(0); Function add(){num.value++; } return {num, add} return {num, add}Copy the code
  • The source code of Reactive is implemented as a Proxy object, which solves the problem that deletion and addition of objects in Vue2.0 cannot trigger response dependencies, and that the special use of arrays does not trigger responsiveness. It is also a proxy Object that exposes us to direct, deep control of objects, and performs better than the wrapper function Object.defineProperty
const obj = reactive({ name:'xxx' }); function changeObj(){ obj.name = 'aaa'; // There is no need to use value here, but note that Vue will not automatically deconstruct the obj object when we return it. } return {obj};} return {obj};} return {obj};Copy the code

Computes attributes

const total = computed(() => { return num.value + obj.age; }); Const total = computed({get(){}, set(value){}})Copy the code

3. Watch and watchEffect

Watch has the same meaning as Vue 2.0. The watchEffect is like a watch with deep: True added, but more powerful

  • Define a listener for a single property
const num = ref(0);
watch(num, (newValue, oldValue) => {
    console.log(newValue, oldValue);
});
Copy the code
  • Define two properties
const num = ref(0); const num2 = ref(1) watch([num, num2], (newValues, oldValues) => { console.log(newValues, oldValues); // newValue and oldValue are arrays containing the new values of num and num2, the same with the latter.Copy the code
  • Listen to reactive reactive objects
watch(obj, (newValue, oldValue) => { console.log(newValue, oldValue); / / note that here no matter how deep is set to true or false, obj child property changes will be detected, and the same as the newValue oldValue, personally think that is a BUG}, {immediate: false, deep: true});Copy the code
  • WatchEffect listening
const num = ref(0);
const obj = reactive({
    name: "xxx",
    age: 10,
});
watchEffect(() => {
    const a = num.value;
    const age = obj.age;
    console.log(a, age);
});
Copy the code

WatchEffect automatically executes a callback when the page is loaded, and all data dependencies called inside the function are monitored, firing whenever one of the monitoring items is changed. The return value, like the return value of watch, is an unlisten function. This listener is also destroyed when a component is destroyed

4. Life cycle

All lifecycle functions in setup are preceded by an on, such as onMount->Vue2. When they are invoked with the equivalent lifecycle of Vue2, they are always invoked before the lifecycle of Vue2

  • The official address: v3.cn.vuejs.org/guide/compo…

5.hooks

* Hook is a writing method that collects and classifies the data or functions we need. We can call the data and functions we need for the corresponding folder, so we don’t have to worry about the problem of too many functions in method that are difficult to maintain

Import {reactive, onMounted} from "vue"; import {reactive, onMounted} from "vue"; import { getData } from "./api" function getTableData() { let obj = reactive({ data:[], }); onMounted(async () => { const res = await this.getData({pageSize:10,pageNum:1}); if(res.code === 200){ data = res.data; }; }); return { obj, }; } export default { getTableData }Copy the code
// we use <template> <h1> </h1> <el-table :data="tableData"></el-table> </template> <script> import { getTableData } from '.. /hooks/getData' export default { setup() { const tableData = getTableData().obj.data; return { tableData } }, }; </script>Copy the code

6. ToRef and toRefs

  • ToRef creates a new REF reactive object for a property on the reactive object, which maintains a reactive connection to the property on the original object. This is useful in attribute passing and decomposition of Props to maintain its responsiveness
const state = reative({
   foo:10
})
cosnt fooRef = toRef(state,'foo');
fooRef.value++; // state.foo=>11
Copy the code
  • ToRefs converts a reactive object into a normal object, where each attribute points to the ref reactive object of the original value. This reactive conversion is deep
const state = reactive({
   a:1,
   b:2
});
const objState = toRefs(state); // {a:ref(a),b:ref(b)}
Copy the code

7. ShallowRef and shallowReactive

  • ShallowRef registered reactive values have a response only for values of primitive data types, not for registered values that reference data types
const num = shallowRef(0); Const obj = shallowRef({y:0 // y does not follow the response because it is an object})Copy the code
  • ShallowReactive Registered responsive objects are only responsive to the first level of properties, but not to the deeper level
Const obj = shallowReactive({a:10, // reactive b:{c:10 // unresponsive}})Copy the code

8. Readonly and shallowReadonly

  • Readonly Returns the read-only proxy for the reactive object
const obj = reactive({ name:'xxx }); const rObj = readonly(obj); // robj.name updates will not be responsive and will issue warningsCopy the code
  • ShallowReadonly The first layer of a reactive object returns a read-only proxy, that is, only the underlying properties are reactive
const obj = reactive({ name:'xxx, a:{ b:10 } }); const rObj = shallowReadonly(obj); // robj.name update is not responsive and will issue a warning; Robj.a.b can be updated in responseCopy the code

9. ToRow and markRow

  • ToRow returns the original object of a reactive object
const obj = {};
const obj1 = reactive(obj);
console.log(obj === toRow(obj)) // true
Copy the code
  • MarkRow marks that an object will never be converted to a Proxy object and returns the object itself

10.customeRef

CustomeRef can customize a ref to display rules that control its responsiveness

Return customRef((track, trigger) => {return {get() {track() // get return value}, Set (newValue) {clearTimeout(timeout) timeout = setTimeout(() => {value = newValue trigger() // trigger update}, delay)}}})Copy the code

Fragment components

In Vue2.0, each template must have a separate root node. An error is reported if there are two sibling root nodes in a template. But Vue3 solves this problem. Vue3.0 uses the Fragment component to collect the root node of the Template to form an independent root node. Multiple levels of nesting of levels are avoided

Teleport components

* Teleport components can encapsulate the component logic we need to separate into any element, reducing nesting and CSS handling

app.component('modal-button', { template: ` <button @click="modalOpen = true"> Open full screen modal! (With teleport!) </button> <teleport to="body"> <div v-if="modalOpen" class="modal"> <div> I'm a teleported modal! (My parent is "body") <button @click="modalOpen = false"> Close </button> </div> </div> </teleport> `, data() { return { modalOpen: false } } })Copy the code

Other changes (relative to Vue2.0)

  • Vue3.0 no longer provides the Vue classes used in Vue2.0. Instead, all operations on Vue are placed on the return value object of createApp(“#app”)
  • The productionTip property is no longer available in Vue3.0, and Vue handles it internally based on the environment.
  • The app Vue3.0. Config. GlobalProperties instead of our former Vue. Property
  • The data option can only be assigned to a function, otherwise an error will be reported
  • The keyboard modifier after Keyup has been removed. The use of Keyup.13 is no longer available, and custom alias keys are no longer supported: vue.config.keycodes
  • Native modifier removed. Native modifier. When you register a click event in a component as a native event, as long as you do not receive a click in the EMIT property, it is considered a native event by default, otherwise it is considered a custom event
  • Remove the filter because it’s not necessary.

Source:www.bilibili.com/video/BV1Zy…