Vue3.x basic notes


Vue3 rewrites with TS

vue-cli3 directory structure

node_modules: Storage dependent packages
public: The static files of the folder will be simply copied without webpack
src: Code folder
dist: File directory generated after packaging
|----assets: Store some of your own static files (pictures) in the project/(font)
|----components: Store custom components (widgets, public components) in the project
|----views: Store custom components in the project (large components, page level components, routing level components)
|----router: storage VueRouter Related documents
|----store: storage Vuex Related documents
|----App.vue Root component
|----main.js entrance js file

Vue3 benefits

  • 1.2 ~ 2 times faster than Vue2.x
  • Compile on demand, smaller than Vue2.x
  • Composite API (similar to React Hooks)
  • Better support for TS
  • Exposed custom rendering API
  • More advanced components

Creating Vue3 projects using Vite

  • Install Vite

    npm install -g create-vite-app
  • Creating vue3 projects with vite

    create-vite-app projectName
  • Install dependent run items

    cd projectName
    npm install 
    npm run dev

Composite API

What is a composite API?

Understanding: encapsulate the data and methods required by a function into a module

Comparison between Vue2 and Vue3

vue2: to develop a function, you need to add a specified data structure in data and a method in methods

vue3 composite API: create a specified method through the setup composite API function entry for return

Each module can be better managed by combining API s

One of Vue3's feature functions: setup

1. The setup function is a function between the two hook functions of the lifecycle function beforeCreate and Created, that is, the data and methods in data and methods cannot be used in the setup function

2. The setup function is the entry to the Composition API

3. The variables and methods defined in the setup function finally need to return, otherwise they can't be used in the template

Precautions for setup function:

1. Since the Created lifecycle method has not been executed when the setup function is executed, the variables and methods of data and methods cannot be used in the setup function

2. Since we cannot use data and methods in the setup function, Vue directly changed this in the setup function to undefined in order to avoid our wrong use

3. The setup function can only be synchronous, not asynchronous


import {ref} from 'vue';
export default {
  name: 'App',
    //Define variables and use ref to make the data change with the new page content
    //Refnote: the ref function can only listen for changes of simple types, not complex types (objects and arrays)
    const count = ref(0);
    //Definition method
    function add(){
    //If you want to use it outside, you must expose the data

In the above example, the page is rendered by listening to data changes through ref, but the ref function can only listen to simple types of data. If you want to listen to complex data types (such as objects and arrays), you need to use the reactive function


import {reactive} from 'vue';
export default {
  name: 'App',
    const {state,removeStu} = useRemoveStu();
    const {stu,addStu} = useAddStu(state);
    return {state,removeStu,stu,addStu}

//Add operation
function useAddStu(state) {
  const stu = reactive({
  function addStu(e){
    let stu1 = Object.assign({},stu.stu);
    stu.stu = {};
  return {stu,addStu}
//Delete operation
function useRemoveStu(){
  const state = reactive({
      {id:1,name:'the other woman',age:12},
      {id:2,name:'Li Si',age:19},
      {id:3,name:'Zhang San',age:20}
  //Delete operation
  function removeStu(index){
    state.stus = state.stus.filter((_item,_index)=>index!=_index)
  return {state,removeStu}

In this way, a function can be encapsulated into a module for use, or methods can be written to different js files and exported through export. When a function needs to be used, the js file can be imported for use

The essence of composite API

Composition API and Option API can be mixed

Composition API: setup function in Vue3

Option API: data and methods attributes in Vue2

The essence of composite API: the essence of composite API is to inject the methods and data in setup function into Option API for use

Reactive and Ref

What is Reactive?

  • reactive is the method of implementing responsive data provided in Vue3
  • In Vue2, responsive data is implemented through defineProperty, while in Vue3, responsive data is implemented through the Proxy of ES6

reactive note

  • The reactive parameter must be an object (json/arr)
  • If other objects are passed to reactive, the modified object interface will not be refreshed by default. If you want to refresh, you can update the interface by re assignment

What is Ref?

Like reactive, ref is also used to implement responsive data. Because reactive must pass an object, it will be very troublesome if we only want to implement responsive data for a variable in enterprise development. Therefore, Vue3 provides us with ref method to monitor simple values

Ref essence: the essence of the bottom layer of ref is actually reactive. The system will automatically convert the value we pass in into ref (xxx) - > reactive ({value: XXX})

Ref notes:

  • The value of Ref used in Vue does not need to be obtained through value
  • The value of Ref used in Js must be obtained through value
  • If the data is created through ref, you do not need to obtain it through. value when using it in the template, because Vue will automatically add. value to us

Difference between ref and reactive

If ref type data is used in the template, Vue will automatically add. value for us

If reactive data is used in the template, Vue will not automatically add. value for us

How does Vue decide whether to add. value automatically

Before parsing the data, Vue will automatically judge whether the data is of ref type. If so, it will automatically add. value. If not, it will not automatically add. value

How does Vue determine whether the current data is ref type

Through current data__ v_ref to judge

If you have this private attribute and the value is true, it means you want to give ref type data

*How to judge whether it is ref type and reactive type?

Judge by introducing isRef method and isReactivce method in vue, and return true/false

import {isRef,isReactive} from 'vue';
import {ref,reactive} from 'vue'
let age = ref(1);
const state = reactive({
    stus:{id:1,name:'Xiao Ming'}
console.log("Is it ref Type:",isRef(age)); //true
console.log("Is it Reactive Type:",isReactive(state)); //true

Recursive listening

By default, both ref and reactive listen recursively. In Vue3, in order to implement data response, it will wrap the data of each layer into a proxy object

Disadvantages: if the amount of data is large, it will consume a lot of performance

Non recursive listening shallowRef / shallowReactive

If the data is of type shallowRef, you can trigger the update of page content through the triggerRef method

By default, the first layer of data will be packaged as proxy objects, and the page content will be updated only when the current data changes

Note: if the data is created through shallowRef, Vue creates it

Application scenario

Generally, ref and reactive are used, that is, we use shallowRef and shallowReactive only when the amount of data to be monitored is large

shallowRef essence

The essence is similar to that of previous refs. shallowRef essentially uses shallowReactive, so it can only listen to value, which is its first layer

Shallowref (10) = = > shallowreactive ({value: 10}) value is its first layer of data


Get the real object referenced by ref/reactive. The interface update cannot be triggered by modifying the real object

toRaw function: improve performance and do something you don't want to change on the page

Characteristics of ref/reactive data type:

Each modification will be monitored and the UI interface will be updated, but this is actually very performance consuming. Therefore, if we do not need to monitor some operations and update the UI interface, we can get the original data through the toRaw method and modify the original data, so that it will not be monitored

Note: if you want to use toRaw to obtain the original data in ref, you must use. Value to obtain it, because the essence of ref is to use reactive to create objects and put references into the value attribute

Namely: let obj = toRaw(state.value);

For example:

​ let user = {name:'xiaoge',age:12}

​ const state = reactive(user); // Reference the user object in the porxy of the reactive wrapper

/ / use toRaw to obtain the original reference object

​ let user2 = toRaw(state);// The incoming reactive object gets the object reference, so user2 === user = true

MarkRaw: using this method will not track this object, that is, no matter how it is changed, the UI page will not be updated, nor can it be updated through the reactive method


Difference between ref and toRef:

Use ref to wrap the attributes in an object. After modification, its original reference value will not be affected, that is, the attribute value in the object will be directly copied to the current Ref,

The page responds after updating the data

toRef will associate the previous objects, and the page will not change after updating the data

    let user = {name:'xiaoge',age:12}
    //Use toRef to reference the properties of an object
    const state = toRef(user,'name');
    //When the property value of the toRef wrapper is modified, the reference object also changes, and the UI will not respond
    function change(){
        state.value = "Xiao Wang";
    return {user,change,state}


When we use toRef, we cannot reference multiple attributes in the object. We can associate multiple attributes by using toRefs

let user = {name:'xiaoming',age:12}
//toRef can only be associated with a single attribute
let name = toRef(user,'name');
let age = toRef(user,'age');
//Using toRefs
let state = toRefs(user);//Will associate all the properties in the object
//Assignment and acquisition operations are performed in this way = 'Xiao Hong';
state.age.value = 10;


Return a ref object, which can explicitly control dependency tracking and trigger response, and customize Ref

I think this is just a custom ref, which can control whether it is responsive and write its own logic in it


function myRef(value){
        return customRef((track,trigger)=>({
                track();//Tell Vue that this data needs to track changes
                return value;
                value = newValue;

Track: Tell Vue that this data needs to track changes

Trigger: trigger data change UI interface

Why use custom ref s?

We can customize a ref in which we can write our own code logic, and most of us need to request external interfaces during development

Normally, send asynchronous request for data response:

    const state = ref([]);
        return res.json();
        state.value = res;
    return {state}

This can be achieved by customizing ref:

import {customRef} from "vue";
//Custom ref
function myRef(value){
        return customRef((track,trigger)=>{
            //Send request
                return res.json();
                value = res;
            return {
                    track();//Tell Vue that this data needs to track changes
                    return value;
                    value = newValue;

//Combined APi entry
    const state = ref([]);
        return res.json();
        state.value = res;
    return {state}

Note: the sending request cannot be put into the get method, because get will be called when displaying data, and the interface will be updated after get is executed, so it will be called repeatedly

Trigger must be called to trigger response after data change

ref get element

In vue2.x, we can mark an element with ref, and then get the element through this.$

In setup in vue3.x, this.$ cannot be used to get elements

In Vue3, the declaration cycle is drawn into one method. If you want to invoke the life cycle in setup, you can import the method directly and write the code in the callback of the declaration cycle.

Unable to get vue built-in method through this.$xxx in setup function

To get the element in setup, you need to mark the ref element and execute it in the mount lifecycle function

	<div ref="box"></div>

    const box = ref(null);
	console.log(box.value);//Print null
	//Mount lifecycle
        console.log(box.value);//Print < div > < / div >
    return {box}

Note: the variable name of the last return must be consistent with the name of the ref tag, otherwise the element cannot be obtained


Readonly: create recursive read-only data, and each layer is read-only

shallowReadonly: only the first layer is read-only

isReadonly: is it a Readonly type

The difference between const and Readonly

  • const: assignment protection, data cannot be re assigned

  • Readonly: property protection, cannot be reassigned

Tags: Javascript Front-end Vue Vue.js

Posted on Sat, 30 Oct 2021 14:27:44 -0400 by conker87