Writing in the front

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Vue3.x has been updated and optimized since its first version of One Piece was released on September 18, 2020. Official documentation in Chinese has also been released; As end users, let’s take a look at what Vue3 has added. Today xiaobian will take you through the comparison with Vue2. X to learn the beginning.

Vue3. X

  • “Performance” : Performance optimization
  • Tree-shaking Support: Supports Tree shaking
  • Composition API: Composition API
  • Fragments, Teleport, Suspense: New components
  • Better TypeScript support: Better TypeScript support
  • Custom Renderer API: Custom Renderer

The scaffold

Scaffolding acts as an entry point for project engineering creation and can be used to quickly create standard Vue projects, as described below in terms of scaffolding compliance.

Vue2.x

  1. Global installation of Vue2. X scaffolding
yarn globalNPM install -g vue/cliCopy the code

Vue3.x

  1. Globally install Vue3. X scaffolding
yarn globalAdd @vue/cli # or NPM install -g@vue /cliCopy the code
  1. It then runs in a Vue project
vue upgrade --next
Copy the code
  1. Project creation
vue create my-project
Copy the code

instructions

Vue3. X can create a Vue2. X project

The life cycle

In vue3. X, a new setup life cycle function is added. The setup life is executed before the beforeCreate life function. In addition, change the names of beforeDestroy to beforeUnmount and destroyed to unmounted for naming unification.

Vue2.x

Life cycle diagram The life cycle

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed
  • errorCaptured

Vue3.x

Life cycle diagram The life cycle

  • setup
  • onBeforeMount
  • onMounted
  • onBeforeUpdate
  • onUpdated
  • onBeforeUnmount
  • onUnmounted
  • onErrorCaptured

table

The life cycle Vue2.x Vue3.x instructions
setup N Y BeforeCreate and created are replaced by setup()
beforeCreate Y setup After instance initialization, data Observer and Event/Watcher event configuration are performed before the component instance is createdPerform some initialization tasks in plug-in development
created Y setup The component instance has been created and configured with data Observer, property and method operations, and Watch/Event event callbacks. But the DOM has not been mounted, and this stage can be used for asynchronous data retrieval
beforeMount Y onBeforeMount Called before the mount begins: The associated render function is called for the first time
mounted Y onMounted After the component instance is mounted, the DOM is created, and this stage can be used to access data and DOM elements, but there is no guarantee that all child components will be mounted together. Use vm.$nextTick inside Mounted if you want the entire view to be rendered
beforeUpdate Y onBeforeUpdate Called before data is updated and can be used to get the state before data is updated. You can manually remove event listeners that have been added here
updated Y onUpdated When this function is executed. The DOM has been updated. Updated does not guarantee that all child components will also be redrawn together. If you want to wait until the entire view is redrawn, use vm.$nextTick in its updated
beforeDestroy Y onBeforeUnmount Called before instance destruction. At this step, the instance is still fully available, at which point you can cancel the timer and subscribe to events
destroyed Y onUnmounted Called after the component instance is unloaded. When this hook is called, all directives of the component instance are unbound, all event listeners are removed, and all child component instances are unloaded
errorCaptured Y onErrorCaptured Error call

Pay attention to

  1. vue3.xThe lifecycle execution takes place invue2.xEarlier in the life cycle
  2. setupThis life cycle occurs whenbeforeCreateandcreatedbefore
  3. Both forms of lifecycle functions can coexist, and both are executed

Code case

<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import { 
    onBeforeMount, 
    onMounted, 
    onBeforeUpdate, 
    onUpdated, 
    onBeforeUnmount, 
    onUnmounted, 
    reactive, 
    ref } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src

@Options({
  props: {
    msg: String
  },
  components: {
    HelloWorld
  }
})
export default class Home extends Vue {
  setup ():void {
  
     console.log("Similar to Created")
    // Mount lifecycle
    onBeforeMount(() = > {
      console.log('Vue3.0 similar to beforeMount ')
    })

    onMounted(() = > {
      console.log('Vue3.0 similar to Mounted ')})// Follow the life cycle of the new phase
    onBeforeUpdate(() = > {
      console.log('Vue3.0 similar to beforeUpdate ')
    })

    onUpdated(() = > {
      console.log('Vue3.0 similar to updated ')})// Destruction phase lifecycle
    onBeforeUnmount(() = > {
      console.log('Vue3.0 similar to beforeDestory ')
    })

    onUnmounted(() = > {
      console.log('Vue3.0 is similar to destoryed')
    })
  }

  beforeCreate (): void {
    console.log('vue2.0 beforeCreate')
  }

  created ():void {
    console.log('vue2.0 created')
  }

  beforeMount ():void {
    console.log('vue2.0 beforeMount')
  }

  mounted ():void {
    console.log('vue2.0 mounted')
  }

  beforeUpdate ():void {
    console.log('vue2.0 beforeUpdate')
  }

  updated ():void {
    console.log('vue2.0 updated')
  }

  beforeUnmount ():void {
    console.log('vue2.0 beforeDestroy')}// destroyed==> unmounted
  unmounted ():void {
    console.log('vue2.0 destroyed')
  }
}
</script>
Copy the code

Vue3 also has a new lifecycle hook. We can access the lifecycle of a component by adding on before the lifecycle function. We can use the following lifecycle hooks:

  • onBeforeMount
  • onMounted
  • onBeforeUpdate
  • onUpdated
  • onBeforeUnmount
  • onUnmounted
  • onErrorCaptured
  • onRenderTracked
  • onRenderTriggered

We mount the lifecycle hook in setup and call the corresponding hook function when the lifecycle is executed:

import { onBeforeMount, onMounted } from "vue";
export default {
  setup() {
    onBeforeMount(() = > {
      // beforeMount code execution
    });
    onMounted(() = > {
      // mounted}); }},Copy the code

Vue3. X new features

Responsive API

  • Vue3.xIn the newreactiveEquivalent to Vue2. XVue.observable
  • reactiveFunction only acceptsobjectandarrayAnd other complex data types
  • refCreate basic data types, such as strings and values

    Reactive deals with complex data structures, whereas REF deals with basic data structures. But the ref itself can also handle objects and arrays:

  1. usereactiveTo create reactive state for JS objects
import { reactive, toRefs } from "vue";
const user = reactive({
  name: 'kuaizhidao'.age: 6}); user.name =Quickwisdom Island
Copy the code
  1. For some basic data types, like strings and numbers, we want it to be reactive, and we can also passreactiveFunction to create objects, butVue3.xAnother function is providedref
import { ref } from "vue";
const num = ref(0);
const str = ref("");
const bool = ref(true);
 
num.value++;
console.log(num.value);
 
str.value = "new val";
console.log(str.value);
 
bool.value = false;
console.log(male.value);
Copy the code

The RefImpl object returned by ref is a RefImpl object containing only one parameter named value, which is obtained and modified in JS through its value property. However, when rendered in the template, the internal values are automatically expanded, so there is no need to append.value to the template.

<template>
  <div>
    <span>{{ count }}</span>
    <button @click="count ++">Increment count</button>
  </div>
</template>
 
<script>
  import { ref } from 'vue'
  export default {
    setup() {
      const count = ref(0)
      return {
        count
      }
    }
  }
</script>
Copy the code
  1. refWork with objects and arrays
import { ref } from "vue";

// Process objects
const obj = ref({
  name: "kuaizhidao".age: 6});setTimeout(() = > {
  obj.value.name = Quickwisdom Island;
}, 1000);
 
// Handle arrays
const list = ref([1.2.3.4.6]);
setTimeout(() = > {
  list.value.push(7);
}, 2000);
Copy the code

Learning web site

  • Vue2.x
  • Vue3.x
  • Fast intellectual island