Introduction:

Vue3 has been the general trend, but the use rate of projects in the society is still not very high, so most of the front-end partners only stay at “heard that Vue3 came out”, what specific changes have been made? I’m not sure. What are the advantages? What features have been added/removed? How much has it changed? Neither is clear. This article aims to clearly explain my understanding of Vue3 version and the difference between Vue2 and Vue3. It doesn’t speak advanced source code, like the guys who start out with Fragment, Suspense, Teleport, tree-shaking, Composition API professional nouns. People we haven’t talked to are confused. This article starts from the basic Vue3 project creation entrance and explains it step by step. If you feel that you have gained something, please click “like” and save it. This article will be updated continuously

Create a Vue3 project

//step1 create a project using the cli
vue create <project_name> 
/ / step2 choice
Default (Vue 3) ([Vue 3] babel, eslint)
// step3 create the vue.config.js file
module.exports = {
  lintOnSave: false,}// Add this sentence in order to turn off esLink check and facilitate our development test
Copy the code

Vue instance creation and mounting

/ / the Vue2 way
import Vue from 'Vue' // Introduce the Vue constructor
const vm = new Vue({
  render:h= > h(App)
});
/ / a mount
vm.$mount('#app')
console.log(vm)

/ / the Vue3 way
import { createApp } from 'vue' // Introduce a factory function called createApp
const app = createApp(App);
/ / a mount
app.mount('#app');
console.log(app)
Copy the code

The way Vue2 is written does not work in Vue3 because the constructor Vue is not imported

We printed them separately in two Vue2 projects and Vue3 projectsvmandappExamples: From the following two images, we can see that the app instantiated by Vue3 is much smaller than the VM instantiated by Vue2. Many methods in Vue2 are not commonly used or even unused. In Vue3, they are not mounted on the instance, which is more lightweight

Template syntax

Open the app. vue file. The only difference with Vue2 is that Template no longer requires a root tag.

The setup function

The setup function is essentially a property and method entry to Vue3. Why data, methods, computed are used in Vue2? In Vue3 we put properties and methods in setup functions. The setup function has the following characteristics:

Setup (props,context): Accepts two parameters

Props: (1) received from the parent component parameters (2) from the context: context, mainly consists of three parameters: attrs, emits, slots, the equivalent of this in Vue2 attrs, emits, slotsCopy the code
props:['msg'].emits: ['eventOne']
// in Vue3, if you use emits, you need to declare in the page that the function was called, like props, otherwise a warning will be given (although it still works).
Copy the code

2. There are two types of return values:

(1) Return object, return object in the attribute method, can be directly used in the template; (2) Return the rendering function, can customize the content of the rendering;Copy the code

3. There is no internal functionthis;

4. If there are internal asynchronous functions, use this functionawaitWhen, can be used directly, do not need insetupThe front andasync;

// The most basic form of writing
import { h } from 'vue'
setup() {
    let name = 'Less face';
    let age = 18;

    function sayhello() {
      alert(I call `${name}I do every year${age}Hello. `)}function changeInfo() {
      name = 'New Face Less';
      age = 28;
      console.log(name,age);
    }
    // 1. Return the object
    return {
      name,age,sayhello,changeInfo
    }
    // 2. Return the render function
    // return ()=> h('h1',name)
  }

Copy the code

ref

When we trigger the changeInfo function above, the data printed in the developer tools has changed, but the page does not respond. In order for Vue to listen for changes in the data, to implement the response, we need to introduce ref to declare, when the variable is bidirectional binding

import{h, ref}from 'vue'
setup() {
    let name = ref('Less face');
    let age = ref(18);

    function sayhello() {
      alert(I call `${name}I do every year${age}Hello. `)}function changeInfo() {
      name.value = 'New Face Less';
      age.value = 28;
      console.log(name,age);
    }
    // 1. Return the object
    return {
      name,age,sayhello,changeInfo
    }
  }
Copy the code

We print age and find that the structure of the variable declared by ref is changed into an object, and the value in it stores our variable. Here is the same as Vue2, the response is realized by defineProperty method and by listening for GET and set methods

Well, what if I declare an object or an array? withrefIt can be done.

let job = ref({
  type:'front-end'.salary:'30k'
})
function changeInfo() {
  job.value = {
    type:'back-end'.salary:'20k'
  }
  console.log(job)
}
Value is a Proxy instance, and ref checks that Object is declared, so reactive is called
// Reactive is an encapsulated Proxy
Copy the code

reactive

import {reactive} from 'vue'
let job = reactive({
      type:'front-end'.salary:'30k'
    })
function changeInfo() {
  job = {
    type:'back-end'.salary:'20k'
  }
  console.log(job)
}
// Job does not need a. Value value
// To make things simpler, we recommend that you use reactive to declare a large object called data and return it
let data = reactive({
    game:' '.number1:1.arr: ['lian'.'yan'.'shao'].person: {
        name:'Less face'.hobby: ['game'.'girl']}})return {data}
// The template can fetch the value of data.value
Copy the code

Reactive is a Proxy that encapsulates ES6. Compare Vue2 to listen on objects and arrays.

Vue2 differs from VUe3 in the principle of response

Vue2

DefineProperty is also used when listening on objects, and recursive judgment is performed. If nested objects are used, all values are recursed to listen

[bug Mc-10868] – overwrite array method when listening on array

  1. 1. Add attributes, delete attributes, the interface does not update, need to callset/delete
  2. 2. Array directly through the subscript modification, page will not update, need to callspliceOr,set

Vue3

setup() {
    let person = {
      name:'Less face'.hobby: ['girl'.'front-end']}let p = new Proxy(person,{}); // Proxy takes two parameters, one for the original object and one for the prototype method

    function changeInfo() {
      console.log('p',p)
      console.log('person',person)
      p.hobby[1] = 'Hey hey hey'
    }
    // 1. Return the object
    return {
      person,changeInfo,p
    }
  }
Copy the code

The data was successfully modified and synchronized to Person, but Vue did not capture the data change and could not perform the page update operation, so it changed the method called.

Overwrite get, set, and deleteProperty methods and do listener (console instead of ~) target: original object, propName: property name, value: However, the source code isn’t written that way either, which directly modifythe person object, and that’s where Reflect comes in

let person = {
    name:'Less face'.age:18
}
const p = new Proxy(person,{
    get(target,propName) {
        console.log('Here is the vUE listening action, get${propName}Attribute `)
        return target[propName]
    },
    set(target,propName,value) {
        console.log('Here is vue update action, modify${propName}Property to update the page ')
        target[propName] = value
    },
    deletePrroperty(target,propName) {
        console.log('Here is the vue update action, deleted${propName}Property to update the page ')
        return delete target[propName]
    }
})
Copy the code

Reflect

Reflect introduces most of the basic Object methods, and replaces everything that basic Object can implement. When we define a variable repeatedly with defineProperty, we get an error. This is bad for single js threads and will block all operations because Vue2 uses a lot of tries… Catch catches such errors, and Reflect returns true/false instead

let person = {
    name:'Less face'.age:18
}
const p = new Proxy(person,{
    get(target,propName) {
        console.log('Here is the vUE listening action, get${propName}Attribute `)
        return Reflect.get(target,paopName)
    },
    set(target,propName,value) {
        console.log('Here is vue update action, modify${propName}Property to update the page ')
        Reflect.set(target,paopName,value)
    },
    deletePrroperty(target,propName) {
        console.log('Here is the vue update action, deleted${propName}Property to update the page ')
        return Reflect.deleteProperty(target,paopName)
    }
})
Copy the code

Here is a quick note: can Vue2 (data, methods, computed) be used in Vue3 projects?

The answer is: yes. but

  1. 1.Vue2I can write it in this wayVue3Data and methods, butVue3Is not availableVue2Data and methods,
  2. 2. WhenVue2andVue3If the declared attributes of theVue3overwriteVue2

conclusion

The next article will continue the analysis of differences between COMPUTED, Watch, life cycle and hooks in Vue2 and Vue3

If you find this article helpful, give me a thumbs up and a little encouragement

Portals for other interesting articles:

  • Learn all the methods in an Array prototype
  • An article on all the methods to master Object prototypes
  • Strange prototype chain cold knowledge (need to have a certain prototype chain foundation to see oh)
  • Vue Photo Amplifier, Album Set: VUE-Photo-Preview
  • Hand touch teaches you to write a responsive page from 0 using Echart