The source code for VuE3 has been open for a long time, and the official website is rushing out new documentation. But my speed can always be compared with that of a snail. As it happens, there is a recent project to do VUE3. Then I will write a “use after feeling”! Share what you learned about VUE3 in the project.

Here is a brief summary of what I think is noteworthy in VUE3:

  • 1. Changes in data interception mechanism
  • 2. Introduction of composite apis
  • 3. A series of surprises from the Setup function
  • 4. Practical application of responsive apis

1. Changes in data interception mechanism

Vue2 intercepts data changes through object.defineProperty (). After upgrading to VUe3, instead of hijacking data with Object.defineProperty, the authors hijacked data using proxy, a new feature of ES6. Because in VUe2, responsive data needs to be pre-defined through data() initialization, but after VUe3, the data in data is no longer responsive tracking, but converted into a proxy proxy for tracking and updating.

Note: In Vue3, it takes any data defined in the data() function and converts it to a proxy proxy by iterating over all properties using getter or setter.


Second, the introduction of composite API

The biggest change in VUe3 is the introduction of the compositionApi, which is a core part of vue3.

Including the following aspects:

  • A, setup function

The details are covered in the next section, but not here.

  • B. Lifecycle hooks

Vue3 throws out a global API to support hook calls in setup functions by introducing the form onX.

  • C, dojo.provide/Inject

Vue3 also supports provide and inject in the setup function, as long as they are introduced in the corresponding location:

import { provide } from 'vue'; setup(){ provide(name, 'hello! '); } import {inject} from 'vue'; setup(){ inject('name', [default-value]: string); }Copy the code

  • D, getCurrentInstance

Support for accessing your own instance in the setup function

import { getCurrentInstance } from 'vue';
setup() {
	const internalInstance = getCurrentInstance();
}
Copy the code

The setup function brings a series of surprises

In VUe3, the introduction of the Setup function, a functional approach to development, brings the code together nicely.

  • In VUe2, data needs to be called this when it is used. In VUe3, reactive, ref is used to set reactive data.
data() { return { name: 'aaa', }; } => const name = ref('aaa'); Just as you can simply define variables, you can initialize them using refCopy the code
  • The setup function replaces the function definition of methods

In the Setup function, we can selectively expose the function we define. In VUe2, functions defined in methods are bound to this. The setup function solves this problem by protecting our own private variables.

methods: { function unkouwnFunc() { console.log(3333); } }, => setup () { function unkownFunc() { console.log(3333); } return {unkownFunc, // after return, this function is bound to the component instance, can be used directly in the template}; }Copy the code
  • About using emit events in setup functions
import { SetupContext } from 'vue';
  	
emits: ['eventName'],
setup(props, ctx: SetupContext){
    ctx.emit('event-name', value);
}
    
Copy the code
  • In addition, to support the setup function, the author throws global lifecycle hooks, which are only valid in the setup function.
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';

setup() {
    onBeforeMount() {
        your code
    }
    onMounted () {
        your code
    }
    onBeforeUpdate() {
        your code
    }
    onUpdated() {
        your code
    }
    onBeforeUnmount() { 
        your code
    }
    onUnmounted() {
        your code
    }
}
Copy the code

4. Practical application of responsive apis

  • Ref Vs Reactive

    Ref is a basic data type creation method that returns a RefImpl object. Value refers to its bound value. If it is used to create an object, its value is returned as a Reactive object.

    A Reactive object returns a proxy proxy that iterates through each property and creates it as an ES6 proxy.

    From the printed data, we can see that the.value of the object type created by the REF data is consistent with the data structure of Reactive. That is, when a REF creates data of object type, the pair is automatically converted to Reactive data.

  • The benefits of the Ref and Reactive apis

    Ref Reactive in VUe3 is very, very useful. Because Vue gives its global API directly here. In any scenario, we can directly import and create this responsive data. Through import, export, code centralized management.

    By centralized management, we mean more flexible use of code. Vue2 used store to centrally manage state, but now we can really get rid of store. Because vue3’s responsive API gives us a nice experience.

>> state.js 
    
  store = {
    state: reactive({
      count: 0,
    })
  };

  export default store;
        
=>
    
import store from 'state.js';
setup() {
  // set count
  store.count = 2;
  // get count
}
Copy the code
  • About the use of computed and watch
computed: {
	aaa() => {
        	return 333
        }
    },
    watch: {
    	bbb(newv, oldv) {
        	console.log(newv, oldv);
        }
    },
}
    

=>
    
import { computed } from 'vue';

const aaa = computed(() => {
  return 333;
})
Copy the code

watch & watchEffect

import {watchEffect, watch} from 'vue'; Watch ((BBB, (current, prev)) => {Your Code}); Watch ([aaa, BBB], ([current, prev], [current2, prev2]) => {Your Code}) Const aaa = ref(0); watchEffect(() => { console.log(aaa.value); });Copy the code

watch VS watchEffect

  • 1. Lazy listening

    WatchEffect only tracks changes and executes the callback function when tracking dependencies. Watch lazily listens for dependencies and does not execute the callback function when tracking dependencies.

  • 2. Support access to current and previous states
  • More specifically, when should the call function be triggered

    Watch has more options than watchEffect. For example, we can retrieve the previous and current state, and determine whether the corresponding callback is performed by the state change.

For more details, please click here.

END TK U