Vue learning notes - 6 Vue3 quick start

Posted by maheshb on Wed, 05 Jan 2022 08:08:55 +0100

Vue learning notes – 6 Vue3 quick start

6. Vue3 get started quickly

6.1 create Vue3 project

6.1. 1 create with Vue cli
## Check the version of @ vue/cli and make sure that the version of @ vue/cli is in 4.5 Above 0
vue --version
vue -V
## Install or upgrade your @ vue/cli
npm install -g @vue/cli
## establish
vue create vue_test
## start-up
cd vue_test
npm run serve
6.1. 2 create with vite
  • vite -- a new generation front-end building tool.

  • Official documents

  • vite official website

  • The advantages are as follows:

    • In the development environment, there is no need for packaging operation, and it can be quickly cold started.
    • Lightweight and fast thermal heavy load (HMR).
    • True on-demand compilation, no longer waiting for the completion of the whole application compilation.
  • Comparison between traditional construction and vite construction

  • Create project
## Create project
npm init vite-app <project-name>
## Enter project directory
cd <project-name>
## Installation dependency
npm install
## function
npm run dev

6.2 common composition APIs

  • [official documents][ ]
6.2. 1 setup to kick off
  • Understanding: vue3 A new configuration item in 0 with the value of a function.

  • setup is the "stage of performance" of all Composition API s.

  • The data, methods, etc. used in the component should be configured in setup.

  • There are two return values of the setup function:

    • If an object is returned, the properties and methods in the object can be used directly in the template. (focus!)

    • If you return a rendering function: you can customize the rendering content. (understand)

  • Note:

    • Try not to contact vue2 X configuration mix

    • Vue2. The properties and methods in setup can be accessed in the X configuration (data, methods, computed...).

    • However, vue2.0 cannot be accessed in setup X configuration (data, metals, computed...).

    • If there are duplicate names, setup takes precedence.

  • setup cannot be an async function, because the return value is no longer the return object, but Promise. The template cannot see the attributes in the return object. (you can also return a Promise instance later, but you need the cooperation of suspend and asynchronous components)

6.2.2 ref function
  • Function: define a responsive data.

  • Syntax:

    const xxx = ref(initValue) 
    • Create a reference object (ref object for short) containing responsive data.
    • Operation data in JS:
    • Read data from template: not required value, direct:
  • remarks:

    • The received data can be basic type or object type.
    • Basic type of data: the response type still depends on object get and set of defineproperty() are completed.
    • Data of object type: internal "help" vue3 A new function in 0 - reactive function.
6.2.3 reactive function
  • Function: define the responsive data of an object type (do not use it for basic types, but use the ref function).

  • Syntax:

    const Proxy object= reactive(Source object) 
    • Receive an object (or array) and return a proxy object (proxy instance object, proxy object for short).
  • reactive defines responsive data as "deep-seated".

  • The internal Proxy implementation based on ES6 operates the internal data of the source object through the Proxy object.

6.2. 4 Vue3. Responsive principle in 0
6.2. 4.1 vue2. Response of X
  • Implementation principle:

    • Object type: through object Defineproperty() intercepts the reading and modification of properties (data hijacking).

    • Array type: intercept by overriding a series of methods to update the array. (the change method of the array is wrapped).

      Object.defineProperty(data, 'count', {
          get () {}, 
          set () {}
  • Problems:

    • If you add or delete attributes, the interface will not be updated.
    • Modify the array directly through subscript, and the interface will not be updated automatically. Vue3.0's response
  • Implementation principle:

    • Proxy: intercepts the changes of any attribute in the object, including reading and writing attribute values, adding attributes, deleting attributes, etc.

    • Through Reflect: operate on the properties of the source object.

    • Proxy and Reflect described in the MDN document:

      new Proxy(data, {
      	// Intercept reading attribute values
          get (target, prop) {
          	return Reflect.get(target, prop)
          // Intercept setting property values or adding new properties
          set (target, prop, value) {
          	return Reflect.set(target, prop, value)
          // Block delete attribute
          deleteProperty (target, prop) {
          	return Reflect.deleteProperty(target, prop)
    = 'tom'   
6.2.5 reactive vs ref
  • From the perspective of defining data:
    • ref is used to define: basic type data.
    • reactive is used to define: object (or array) type data.
    • Note: ref can also be used to define object (or array) type data. It will be automatically converted into proxy object through reactive.
  • From the perspective of principle:
    • ref through object get and set of defineproperty () to implement responsive (data hijacking).
    • reactive implements responsive (data hijacking) by using Proxy, and operates the data inside the source object through Reflect.
  • From the perspective of use:
    • ref defined data: required for operation data Value, which is not required for direct reading in the template when reading data value .
    • reactive defined data: neither operation data nor read data: required value .
6.2. 6 two points for attention in setup
  • Timing of setup execution:
    • Execute once before beforeCreate. this is undefined.
  • setup parameters:
    • props: the value is an object, including the attributes passed from outside the component and declared and received inside the component.
    • Context: context object:
      • Attrs: the value is an object, including: attributes passed from outside the component but not declared in the props configuration, which is equivalent to this$ attrs .
      • Slots: received slot content, equivalent to this$ slots .
      • Emit: a function that distributes custom events, equivalent to this$ emit .
6.2. 7 calculated function of calculated attribute
  • With vue2 The computed configuration function in X is consistent. It is written as follows:
import {computed} from 'vue'

	//Calculation properties - Abbreviations
    let fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
    //Calculation properties - complete
    let fullName = computed({
            return person.firstName + '-' + person.lastName
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
6.2. 8. Watch function
  • With vue2 The watch configuration function in X is consistent.

  • Two small "pits":

    • When monitoring reactive defined responsive data: oldValue cannot be obtained correctly, and deep monitoring is forced on (deep configuration is invalid).
    • When monitoring a property in reactive defined responsive data: the deep configuration is valid.
//Scenario 1: monitor the responsive data defined by ref
	console.log('sum Changed',newValue,oldValue)

//Scenario 2: monitor the responsive data defined by multiple ref s
	console.log('sum or msg Changed',newValue,oldValue)

/* Scenario 3: monitor reactive defined responsive data
			If the watch monitors the reactive data, the oldValue cannot be obtained correctly!!
			If the watch monitors responsive data defined by reactive, the deep monitoring is forced on 
	console.log('person Changed',newValue,oldValue)
},{immediate:true,deep:false}) //The deep configuration here no longer works

//Scenario 4: monitor an attribute in the responsive data defined by reactive
	console.log('person of job Changed',newValue,oldValue)

//Scenario 5: monitor some attributes in the reactive data defined by reactive
	console.log('person of job Changed',newValue,oldValue)

//exceptional case
    console.log('person of job Changed',newValue,oldValue)
},{deep:true}) //Here, the deep configuration is valid because it monitors an attribute in the object defined by the reactive element
6.2.8 watchEffect function
  • The routine of watch is to specify both the monitored properties and the monitored callbacks.

  • The routine of watchEffect is: you don't need to specify which attribute to monitor, and which attribute is used in the monitored callback, then monitor which attribute.

  • watchEffect is a bit like computed:

    • However, computed focuses on the calculated value (the return value of the callback function), so the return value must be written.
    • watchEffect pays more attention to the process (the function body of the callback function), so there is no need to write the return value.
//As long as the data used in the callback specified by watchEffect changes, the callback will be directly re executed.
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect The configured callback was executed')
6.2. 9 life cycle
  • Atlas

  • Vue3. Vue2.0 can continue to be used in 0 Life cycle hooks in X, but two have been renamed:

      beforeDestroy ===> beforeUnmount 
      destroyed ===> unmounted
  • Vue3.0 also provides a lifecycle hook in the form of Composition API, which is similar to vue2 The corresponding relationship of hooks in X is as follows:

    beforeCreate ===> setup()
    created ===> setup()
    beforeMount ===> onBeforeMount
    mounted ===> onMounted
    beforeUpdate ===> onBeforeUpdate
    updated ===> onUpdated
    beforeUnmount ===> onBeforeUnmount
    unmounted ==> onUnmounted
6.2. 10 custom hook function
  • hook -- essentially a function, encapsulating the Composition API used in the setup function.

  • Similar to vue2 mixin in X.

  • Advantages of custom hook: reuse code to make the logic in setup clearer and easier to understand.

  • Custom hook: define a hook that captures mouse click coordinates. The code is as follows:

// usePoint.js
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export default function (){
	//Realize the data related to mouse "dot"
	let point = reactive({

	//Method for realizing mouse "dot" related
	function savePoint(event){
		point.x = event.pageX
		point.y = event.pageY

	//Realize the life cycle hook related to mouse "dot"


	return point
  • Introduce and use in other components:
	<h2>I am Test assembly</h2>
	<h2>The coordinates of the mouse when clicking are: x: {{point.x}},y: {{point.y}}</h2>

	import usePoint from '../hooks/usePoint'
	export default {
			const point = usePoint()
			return {point}
6.2.11 toRef
  • Function: create a ref object whose value points to an attribute in another object. Syntax:
const name = toRef(person,'name')
  • Application: when you want to provide a property in a responsive object separately for external use.

  • Extension: the function of toRefs is the same as that of toRef, but multiple ref objects can be created in batch. Syntax:

toRefs(person) // Only the first layer of data is created as a ref object

6.3 other composition APIs

6.3.1 shallowReactive and shallowRef
  • shallowReactive: handles only the response of the outermost attribute of the object (shallow response).
  • shallowRef: only the response of basic data type is processed, and the response of object is not processed.
  • When will it be used?
    • If there is an object data, the structure is relatively deep, but only the outer attribute changes = = = > shallowreactive.
    • If there is an object data, the subsequent functions will not modify the attributes in the object, but generate a new object to replace = = = > shallowref.
6.3.2 readonly and shallowReadonly
  • readonly: make a responsive data read-only (deep read-only).
  • shallowReadonly: make a responsive data read-only (shallow read-only).
  • Application scenario: when you do not want the data to be modified.
6.3.3 toRaw and markRaw
  • toRaw:

    • Function: convert a responsive object generated by reactive into a normal object.
    • Usage scenario: it is used to read the ordinary object corresponding to the responsive object. All operations on this ordinary object will not cause page update.
  • markRaw:

    • Purpose: mark an object so that it will never become a responsive object again.

    • Application scenario:

      • Some values should not be set to be responsive, such as complex third-party class libraries.

      • Skipping responsive transformations can improve performance when rendering large lists with immutable data sources.

6.3.4 customRef
  • Function: create a custom ref and explicitly control its dependency tracking and update trigger.
  • Achieve anti shake effect:
	<input type="text" v-model="keyword">

	import {ref,customRef} from 'vue'
	export default {
			// let keyword = ref('hello ') / / use the built-in ref prepared by Vue
			// Customize a myRef
			function myRef(value,delay){
				let timer
				// Customize through customRef
				return customRef((track,trigger)=>{
							track() // Tell Vue that this value needs to be "tracked"
							return value
							timer = setTimeout(()=>{
								value = newValue
								trigger() // Tell Vue to update the interface
			let keyword = myRef('hello',500) // Use programmer defined ref
			return {
6.3.5 provide and inject
  • Function: realize communication between progeny and descendant components
  • Routine: the parent component has a provide option to provide data, and the descendant component has an inject option to start using these data.
  • In the parent assembly:
    let car = reactive({name:'Benz',price:'40 ten thousand'})
    provide('car',car)  // Provide data car to descendant components
  • In descendant components:
    const car = inject('car')  // Descendant component accepts data car
    return {car}
6.3. 6 judgment of responsive data
  • isRef: check whether a value is a ref object.
  • isReactive: checks whether an object is a reactive proxy created by reactive.
  • isReadonly: checks whether an object is a read-only proxy created by readonly.
  • isProxy: check whether an object is a proxy created by the reactive or readonly method.

6.4 advantages of composition API

6.4. 1. Problems in options API
  • If you use the traditional options API to add or modify a requirement, you need to modify it in data, methods and calculated respectively.
6.4. 2. Advantages of composition API
  • We can organize our code and functions more gracefully. Let the code of related functions be more orderly organized together.

6.5 new components

6.5.1 Fragment
  • In Vue2: the component must have a root label.
  • In Vue3: components can have no root tag, and multiple tags will be included in a Fragment virtual element.
  • Benefits: reduce tag levels and memory usage.
6.5.2 Teleport
  • Teleport -- is a technology that can move our component html structure to a specified location.
		<button @click="isShow = true">Let me pop a window</button>
		<teleport to="body"> <!-- Insert directly during presentation html In the page body In label -->
			<div v-if="isShow" class="mask">
				<div class="dialog">
					<h3>I am a pop-up window</h3>
					<h4>Some content</h4>
					<h4>Some content</h4>
					<h4>Some content</h4>
					<button @click="isShow = false">Close pop-up window</button>

	import {ref} from 'vue'
	export default {
			let isShow = ref(false)
			return {isShow}

	.mask{  /* Modal box occlusion style */
		position: absolute;
		top: 0;bottom: 0;left: 0;right: 0;
		background-color: rgba(0, 0, 0, 0.5);
	.dialog{ /* Set the pop-up window position in the center of the window */
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		text-align: center;
		width: 300px;
		height: 300px;
		background-color: green;
6.5.3 Suspense
  • Render some additional content while waiting for asynchronous components to give the application a better user experience

  • Use steps:

    • Asynchronous import component
    import {defineAsyncComponent} from 'vue'
    const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
    • Use suspend to wrap components, and configure default and fallback
    	<div class="app">
    		<h3>I am App assembly</h3>
    			<template v-slot:default> <!-- Successful default presentation section -->
    			<template v-slot:fallback> <!-- Failure presentation section -->

6.6 others

6.6. 1. Transfer of global API
  • Vue 2.x has many global API s and configurations.

    • For example, register global components, register global instructions, etc.
    //Register global components
    Vue.component('MyButton', {
      data: () => ({
        count: 0
      template: '<button @click="count++">Clicked {{ count }} times.</button>'
    //Register global directives
    Vue.directive('focus', {
      inserted: el => el.focus()
  • Vue3. These APIs have been adjusted in 0: the global API, that is, Vue XXX is adjusted to the application instance (app):

    2.x global API (Vue)3.x instance API (APP)
6.6. 2 other changes
  • The data option should always be declared as a function.

  • Excessive class name change:

    • Vue2. How to write X:
    .v-leave-to {
      opacity: 0;
    .v-enter-to {
      opacity: 1;
    • Vue3.x writing
    .v-leave-to {
      opacity: 0;
    .v-enter-to {
      opacity: 1;
  • Remove keyCode as the modifier of v-on and no longer support config Keycodes (key codes and custom key names are invalid).

  • Remove v-on Native modifier:

    • Binding events in parent component:
      v-on:close="handleComponentEvent" // Custom event
      v-on:click="handleNativeClickEvent" // Native event
    • Custom events declared in subcomponents:
      export default {
        emits: ['close'] // Declared events are custom events, and those not declared here are native events by default
  • Remove filter: Although the filter looks convenient, it needs a custom syntax to break the assumption that the expression in braces is "only JavaScript", which not only has learning cost, but also has implementation cost! It is recommended to replace the filter with method call or calculation attribute.

Topics: Front-end Vue.js