The official document: [v3.cn.vuejs.org/guide/insta…].

Six highlights of Vue3. X

  • Preformance: performance is better than Vue2. X
  • Tree Shaking Support: Compiled on demand, smaller than Vue2. X
  • Composition API(like React Hooks)
  • Better Typescript Support: Better TS support
  • Custom Renderer API: Exposes Custom rendering apis
  • Fragments,Teleport(Protal),Suspense: More Advanced components

How does Vue3. X get faster

1. Diff algorithm optimization
  • The virtual DOM in Vue2 is a full comparison
  • Vue3 has added a static flag: When comparing with the last virtual node, only nodes with patch flags are compared, and the specific content of the current node to be compared can be learned from the information of the flag
2. Static promotion
  • Vue2 elements are recreated each time regardless of whether they participate in updates and then rendered
  • Vue3 does static promotion for elements that do not participate in the update, which are created only once and reused directly during rendering
3. Event listener cache
  • By default, events are considered dynamically bound, so they are tracked each time
  • But because it is the same function, there is no trace of the change, and can be directly cached and reused

3. Install

1. Install VUE-Three through vuE-CLI scaffolding
  • More stable than Vite
  • This is the same as installing VUe2, except when selecting, select Install 3
/ / install vue - cli
npm install -g @vue/cli    
cnpm install -g @vue/cli 
yarn global add @vue/cli

vue create vue-three
cd vue-three
npm run serve
Copy the code
2. Install vuE-three by Vite scaffold
  • Lighter than vuE-CLI
// NPM or CNPM
npm init vite-app vue-three
cd vue-three
npm install
npm run dev

// yarn
yarn create vite-app vue-three
cd vue-three
yarn
yarn dev
Copy the code

4. Composition API

1. Set up: Composite API entry

Reactive: Defines the bidirectional binding of objects
setup () {
  const myInform = reactive ({
      age: 18.// Define an age attribute with a value of 18
      nextAge:computed (() = > myInform.age + 1) // Evaluate the property, incrementing the age value by 1 each time
    })
  return {myInform} // The defined value is returned
}
Copy the code
3. Ref: Define js base type/define object bidirectional binding
setup () {
  const myName = ref('Tangli Pear fried snow 1226')
  const myInform = ref ({
      name: 'Tangli Pear fried snow 1226'.age: 18
    })
  return {myName, myInform} // The defined value is returned
}
Copy the code
4. ToRefs: Deconstruct objects
// Return this object directly, so that when used, it needs to be accessed
<div>{{myInform.name}}</div>
<div>{{myInform.age}}</div>

setup () {
  const myInform = reactive ({
      name: 'Tangli Pear fried snow 1226'.age: 18
    })
  return {myInform} // The defined value is returned
}
Copy the code
  • Destruct objects using toRefs
// Direct access
<div>{{name}}</div>
<div>{{age}}</div>

setup () {
  const myInform = reactive ({
      name: 'Tangli Pear fried snow 1226'.age: 18
    })
  return{... toRefs(myInform)} }Copy the code
5. Watch: listening in
watch(source,callback,[options])
/ / source: specify the listener response type variable/String, Object, Function, Array
// callback: callback function
// options: deep,immediate,flush
Copy the code
<template>
  <div class="HelloWorld">
    <div>{{age}}</div>
    <div>{{nextAge}}</div>
  </div>
</template>

<script>
import {reactive,computed,onMounted,onUnmounted,toRefs,watch} from "vue";
export default {
  name: "HelloWorld".setup() {
    const { age, nextAge } = userCounter(); 
    / / listener
    watch (age, (newValue,oldValue) = >{
      console.log('New value:' + newValue,'Old value:' + oldValue)
    })
    return{ age, nextAge, }; }};// You can pull the method out
function userCounter() {
  const data = reactive({
    age: 2.nextAge: computed(() = > data.age + 1)});let timer;
  onMounted(() = > {
    timer = setInterval(() = > {
      data.age++;
    }, 1000);
  });
  onUnmounted(() = > {
    clearInterval(timer);
  });
  return toRefs(data);
}
</script>
Copy the code

6.watchEffect

7.computed

5. Lifecycle hooks

1. BeforeCreate, created, setup execution sequence and vue3. The use of x

Vue3. x is compatible with vue2.x downwards, which means that the beforeCreate and created changes are set up in vue3.xCopy the code
beforeCreate ----- set up
created ----- set up
beforeMount ----- onBeforeMount
mounted ----- onMounted
beforeUpdate ----- onBeforeUpdate
update ----- onUpdate
beforeDestory ----- onBeforeUnmount
destory ----- onUnmounted
activated ---- onActivated
deactivated ---- onDeactivated
errorCaptured ---- onErrorCaptured
Copy the code
Vue3. X added two life cycles onRenderTracked onRenderTriggeredCopy the code

Six Teleport.

1. Portal component, which provides a brief way to specify the parent element of the content
2. Examples:
  • You want to display a pop-up Dialog inside the component, and you want the rendered DOM structure not nested inside the component’s DOM
  • The parent component
<template> <! -- Modal box --><Dialog></Dialog>
</template>

<script>
import Dialog from "./Dialog.vue";
export default {
  name: "HelloWorld".components: {Dialog},
  setup(){}};</script>
Copy the code
  • Child components
<template>
  <button class="open" @click="modelShow = true">Click to open the modal box</button><! Teleport the contents of the popover with the to attribute pointing to the ID attribute --><teleport to="#app"> 
    <div v-if="modelShow" class="content">content<button class="open" @click="modelShow = false">Close open the modal box</button>
    </div>
  </teleport>
</template>

<script>
import { ref } from "vue";
export default {
  name: "dialog_box".setup() {
    const modelShow = ref(false);
    return{ modelShow }; }};</script>

<style scoped>
.content {
  position: absolute;
  width: 100%;
  height: 100%;
  background: pink;
  top: 30%;
  width: 200px;
  height: 200px;
  left: 40%;
}
</style>
Copy the code
  • rendering

  • Content is the same as app

Seven fragments.

1. In vue2. X, only one root node is allowed
2. In vue3. X, multiple root nodes are allowed

Eight. Emits Component Option

1. User-defined events sent by components in vue3.x must be defined in emits
2. Examples:
  • The parent component
<template>
  <div class="helloWorld">
    <! -- Custom event from child to parent -->
    <Emits @click="emitClick"></Emits>
  </div>
</template>

<script>
import Emits from "./Emits.vue";
export default {
  name: "HelloWorld".components: {Emits},
  methods: {
    emitClick() {
      console.log('I got clicked.')}}};</script>
<style scoped>
.helloWorld {
  width: 100%;
  /* height: 100%; * /
}
</style>
Copy the code
  • Child components
<template>
  <div @click="$emit('click')">Click me!!</div>
</template>

<script>
export default{}</script>

<style lang="scss" scoped>

</style>
Copy the code
  • The effect

  • Click once, output twice, here is a big pit !!!!!!
  • To solve
<template>
  <div @click="$emit('click')">Click me!!</div>
</template>

<script>
export default {
  emits: ['click'] // Can better solve the problem of duplicate output
}
</script>

<style lang="scss" scoped>

</style>
Copy the code
3. For the above example, if you don’t use an alternative form of emits: [‘click’]
  • The parent component
<template>
  <div class="helloWorld">
    <! -- Custom event from child to parent -->
    <Emits @my-click="emitClick"></Emits>
  </div>
</template>

<script>
import Emits from "./Emits.vue";
export default {
  name: "HelloWorld".components: {Emits},
  methods: {
    emitClick() {
      console.log('I got clicked.')}}};</script>
<style scoped>
.helloWorld {
  width: 100%;
  /* height: 100%; * /
}
</style>
Copy the code
  • Child components
<template>
  ['click'] emits: ['click']
  <div @click="$emit('my-click')">Click me!!</div>
</template>
Copy the code

Nine. Tree shaking optimization

1. Example: nextTick
// vue2.x
// The Vue constructor touches directly
import Vue from 'vue'
Vue.nextTick(() = >{})
Copy the code
// vue3.x
// Extract individual functions and package them to see if they are called
import {nextTick} from 'vue'
nextTick(() = >{})
Copy the code

Ten. V – model

1. V-model principle of VUe2. X
  • The core is get and set interception via Object.defineProperty
  • :value + @input
  • Refer to the link: https://blog.csdn.net/Dobility/article/details/110147985
2. V-model principle of VUe3. X
  • The parent component
<template>
  <div class="helloWorld">
    <! -- Two-way binding of v-model data -->
    <Mymodel v-model:myCounter="myCounter"></Mymodel>
  </div>
</template>

<script>
import { ref } from 'vue'
import Mymodel from "./Mymodel.vue";
export default {
  name: "HelloWorld".components: {Mymodel},
  setup() {
    const myCounter = ref(0)
    return {myCounter}
  }
};

</script>
<style scoped>
.helloWorld {
  width: 100%;
  /* height: 100%; * /
}
</style>
Copy the code
  • Child components
<template>
  <div @click="$emit('update:myCounter',myCounter + 1)">
    myCounter:{{myCounter}}
  </div>
</template>

<script>
export default {
  props: {
    myCounter: {
      type: Number.default: 1}}}</script>
Copy the code