2022 + vue3 quick start + learning route of the latest front-end development knowledge points

Quick start with Vue3

node configuration

1. Introduction to Vue3

1. Performance improvement

  • 41% reduction in bundle size

  • 55% faster initial render, 133% faster update render

  • 54% less memory

2. Source code upgrade

  • Use Proxy instead of defineProperty to achieve responsiveness

  • Rewrite the implementation of virtual DOM and Tree-Shaking

3. Embrace TypeScript

  • Vue3 can better support TypeScript

4. New features

  1. Composition API (composition API)

    • setup configuration
    • ref and reactive
    • watch与watchEffect
    • provide and inject
  2. new built-ins

    • Fragment
    • Teleport
    • Suspense
  3. other changes

    • new lifecycle hook
    • The data option should always be declared as a function
    • Remove keyCode support as v-on modifier

1. Create a Vue3.0 project

1. Use vue-cli to create

Official document: https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create

## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve

2. Use vite to create

Official document: https://v3.cn.vuejs.org/guide/installation.html#vite

Vite official website: https://vitejs.cn

  • What is vite? — A new generation of front-end build tools.
  • The advantages are as follows:
    • In the development environment, no packaging operation is required, and it can be cold started quickly.
    • Lightweight and fast Hot Reload (HMR).
    • True on-demand compilation, no longer waiting for the entire application to be compiled.
## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install
## 运行
npm run dev

2. Common Composition API

Official document: https://v3.cn.vuejs.org/guide/composition-api-introduction.html

1. Kick off the setup

  1. Understanding: A new configuration item in Vue3.0, the value is a function.
  2. setup is all Composition API (composition API) "performance stage" .
  3. The components used in the components: data, methods, etc., must be configured in the setup.
  4. Two return values ​​of the setup function:
    1. If an object is returned, the properties and methods in the object can be used directly in the template. (Focus!)
    2. If it returns a rendering function: you can customize the rendering content. (learn)
  5. important point:
    1. Try not to mix with Vue2.x configuration
      • Properties and methods in setup can be accessed in Vue2.x configuration (data, methos, computed...) .
      • But Vue2.x configuration (data, methos, computed...) cannot be accessed in setup .
      • If there are duplicate names, setup takes precedence.
    2. setup cannot be an async function, because the return value is no longer the return object, but a promise, and the template cannot see the properties in the return object. (You can also return a Promise instance later, but it requires the cooperation of Suspense and asynchronous components)

2.ref function

  • Role: Define a responsive data
  • grammar:const xxx = ref(initValue)
    • Create a reference object (reference object, ref object for short) that contains responsive data .
    • Data manipulation in JS:xxx.value
    • Read data in the template: No need for .value, directly:<div>{ {xxx}}</div>
  • Remark:
    • The received data can be: basic type or object type.
    • Basic types of data: Reactive is still dependable Object.defineProperty()and getcomplete set.
    • Object type data: internally "rescues" a new function in Vue3.0 - reactivefunction.

3. reactive function

  • Function: Define an object type of responsive data (do not use it for basic types, but use reffunctions)
  • Syntax: const 代理对象= reactive(源对象)Receive an object (or array) and return a proxy object (the instance object of Proxy, referred to as proxy object)
  • The reactive data defined by reactive is "deep".
  • The internal ES6-based Proxy implementation operates on the internal data of the source object through the proxy object.

4. Responsive principle in Vue3.0

Responsiveness of vue2.x

  • Implementation principle:

    • Object type: Object.defineProperty()Intercept (data hijacking) by reading and modifying properties.

    • Array type: interception is achieved by overriding a series of methods for updating the array. (The change method of the array is wrapped).

      Object.defineProperty(data, 'count', {
              
              
          get () {
              
              }, 
          set () {
              
              }
      })
      
  • There is a problem:

    • When adding or deleting attributes, the interface will not be updated.
    • Modify the array directly through the subscript, and the interface will not be automatically updated.

Responsiveness of Vue3.0

  • Realization principle:
    • Through Proxy (proxy): Intercept the change of any attribute in the object, including: reading and writing attribute values, adding attributes, deleting attributes, etc.
    • Through Reflect (reflection): operate on the properties of the source object.
    • Proxy and Reflect described in the MDN document:
      • Proxy:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy

      • Reflect:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect

        new Proxy(data, {
                  
                  
        	// 拦截读取属性值
            get (target, prop) {
                  
                  
            	return Reflect.get(target, prop)
            },
            // 拦截设置属性值或添加新属性
            set (target, prop, value) {
                  
                  
            	return Reflect.set(target, prop, value)
            },
            // 拦截删除属性
            deleteProperty (target, prop) {
                  
                  
            	return Reflect.deleteProperty(target, prop)
            }
        })
        
        proxy.name = 'tom'   
        

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 .
    • Remarks: ref can also be used to define object (or array) type data , which will be automatically converted to reactivea proxy object internally .
  • From the perspective of principle comparison:
    • ref implements responsiveness (data hijacking) Object.defineProperty()through getAND .set
    • reactive implements responsiveness (data hijacking) by using Proxy , and manipulates the data inside the source object through Reflect .
  • From a usage point of view:
    • Data defined by ref: required for.value data manipulation , but not required.value for direct reading in the template when reading data .
    • The data defined by reactive: operation data and read data: neither is required.value .

6. Two points of attention for setup

  • The timing of setup execution

    • Executed once before beforeCreate, this is undefined.
  • parameter of setup

    • props: The value is an object, including: the properties passed from outside the component and received by the internal declaration of 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, equivalent to this.$attrs.
      • slots: Received slot content, equivalent to this.$slots.
      • emit: A function that dispatches custom events, equivalent to this.$emit.

7. Computed properties and monitoring

1.computed function

  • Consistent with the computed configuration function in Vue2.x

  • wording

    import {
          
          computed} from 'vue'
    
    setup(){
          
          
        ...
    	//计算属性——简写
        let fullName = computed(()=>{
          
          
            return person.firstName + '-' + person.lastName
        })
        //计算属性——完整,一般简单的就可以了
        let fullName = computed({
          
          
            get(){
          
          
                return person.firstName + '-' + person.lastName
            },
            set(value){
          
          
                const nameArr = value.split('-')
                person.firstName = nameArr[0]
                person.lastName = nameArr[1]
            }
        })
    }
    

2. watch function

  • Consistent with the watch configuration function in Vue2.x

  • Two small "pits":

    • When monitoring the responsive data defined by reactive: oldValue cannot be obtained correctly, and deep monitoring is forcibly enabled (the deep configuration is invalid).
    • When monitoring an attribute in the reactive data defined by reactive: the deep configuration is valid.
    // 来自尚硅谷老师的代码,参考
    //情况一:监视ref定义的响应式数据
    watch(sum,(newValue,oldValue)=>{
          
          
    	console.log('sum变化了',newValue,oldValue)
    },{
          
          immediate:true})
    
    //情况二:监视多个ref定义的响应式数据
    watch([sum,msg],(newValue,oldValue)=>{
          
          
    	console.log('sum或msg变化了',newValue,oldValue)
    }) 
    
    /* 情况三:监视reactive定义的响应式数据
    			若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
    			若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 
    */
    watch(person,(newValue,oldValue)=>{
          
          
    	console.log('person变化了',newValue,oldValue)
    },{
          
          immediate:true,deep:false}) //此处的deep配置不再奏效
    
    //情况四:监视reactive定义的响应式数据中的某个属性
    watch(()=>person.job,(newValue,oldValue)=>{
          
          
    	console.log('person的job变化了',newValue,oldValue)
    },{
          
          immediate:true,deep:true}) 
    
    //情况五:监视reactive定义的响应式数据中的某些属性
    watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
          
          
    	console.log('person的job变化了',newValue,oldValue)
    },{
          
          immediate:true,deep:true})
    
    //特殊情况
    watch(()=>person.job,(newValue,oldValue)=>{
          
          
        console.log('person的job变化了',newValue,oldValue)
    },{
          
          deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效
    

3. watchEffect function

  • The routine of watch is: specify not only the attribute of monitoring, but also the callback of monitoring.

  • The routine of watchEffect is: no need to specify which attribute to monitor, which attribute is used in the monitoring callback, then which attribute to monitor.

  • watchEffect is a bit like computed:

    • But computed pays attention to the calculated value (the return value of the callback function), so the return value must be written.
    • And watchEffect pays more attention to the process (the function body of the callback function), so there is no need to write the return value.
    //watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
    watchEffect(()=>{
          
          
        const x1 = sum.value
        const x2 = person.age
        console.log('watchEffect配置的回调执行了')
    })
    

8. Life cycle

The life cycle of vue2.x lifecycle_2
The life cycle of vue3.0 lifecycle_2

view2
The above is the life cycle of vue2

8.1 Changes

The life cycle is all written in the setup

  • beforeDestroy was renamed to beforeUnmount
  • destroyed changed its name to unmounted
  • beforeCreate=> setup
  • created => setup
  • beforeMount => onBeforeMount
  • mounted => onMounted
  • beforeUpdate => onBeforeUpdate
  • updated => onUpdated
  • beforeUnmount => onBeforeUnmount
  • unmounted => onUnmounted

8.2 Grammar

setup() {
    
    
    onMounted(() => {
    
    
      console.log('mounted')
    })
  • The lifecycle hooks in Vue2.x can continue to be used in Vue3.0, but two of them have been renamed:
    • beforeDestroyrename tobeforeUnmount
    • destroyedrename tounmounted
  • Vue3.0 also provides lifecycle hooks in the form of Composition API, and the corresponding relationship with the hooks in Vue2.x is as follows:
    • beforeCreate===>setup()
    • created=======>setup()
    • beforeMount ===>onBeforeMount
    • mounted=======>onMounted
    • beforeUpdate===>onBeforeUpdate
    • updated =======>onUpdated
    • beforeUnmount ==>onBeforeUnmount
    • unmounted =====>onUnmounted

9. Custom hook function

  • What are hooks? —— It is essentially a function that encapsulates the Composition API used in the setup function.

  • Similar to mixin in vue2.x.

  • Advantages of custom hooks: code reuse, making the logic in setup clearer and easier to understand.

10.toRef

  • Function: Create a ref object whose value points to an attribute in another object.

  • grammar:const name = toRef(person,'name')

  • Application: When you want to provide a property in the responsive object for external use alone.

  • Extension: Same toRefsas toRefthe function, but multiple ref objects can be created in batches, syntax:toRefs(person)

3. Other Composition APIs

1.shallowReactive 与 shallowRef

  • shallowReactive: only handles the response (shallow response) of the outermost properties of the object.

  • shallowRef: only handles the response of basic data types, not the response of objects.

  • When to use it?

    • 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 function will not modify the properties in the object, but generate a new object to replace ===> shallowRef.

2.readonly 与 shallowReadonly

  • readonly: Make a reactive data read-only (deep read-only).
  • shallowReadonly: Make a responsive data read-only (shallow read-only).
  • Application scenario: When the data is not expected to be modified.

3. toRaw and markRaw

  • toRaw:
    • Function: Convert a responsive objectreactive generated by a bot into a normal object .
    • Usage scenario: It is used to read the common object corresponding to the responsive object. All operations on this common object will not cause page updates.
  • markRaw:
    • Role: Mark an object so that it will never become a responsive object again.
    • Application scenario:
      1. Some values ​​should not be set responsive, such as complex third-party libraries, etc.
      2. Skipping reactive transformations can improve performance when rendering large lists with immutable data sources.

4.customRef

  • Role: Create a custom ref with explicit control over its dependency tracking and update triggering.

  • To achieve the anti-shake effect:

    <template>
    	<input type="text" v-model="keyword">
    	<h3>{
         
         {keyword}}</h3>
    </template>
    
    <script>
    	import {ref,customRef} from 'vue'
    	export default {
    		name:'Demo',
    		setup(){
    			// let keyword = ref('hello') //使用Vue准备好的内置ref
    			//自定义一个myRef
    			function myRef(value,delay){
    				let timer
    				//通过customRef去实现自定义
    				return customRef((track,trigger)=>{
    					return{
    						get(){
    							track() //告诉Vue这个value值是需要被“追踪”的
    							return value
    						},
    						set(newValue){
    							clearTimeout(timer)
    							timer = setTimeout(()=>{
    								value = newValue
    								trigger() //告诉Vue去更新界面
    							},delay)
    						}
    					}
    				})
    			}
    			let keyword = myRef('hello',500) //使用程序员自定义的ref
    			return {
    				keyword
    			}
    		}
    	}
    </script>
    

5.provide and inject

  • Role: Realize communication between ancestor and descendant components

  • Routine: the parent component has an provideoption to provide data, and the descendant components have an injectoption to start using this data

  • Specifically written:

    1. In the parent component:

      setup(){
              
              
      	......
          let car = reactive({
              
              name:'奔驰',price:'40万'})
          provide('car',car)
          ......
      }
      
    2. In descendant components:

      setup(props,context){
              
              
      	......
          const car = inject('car')
          return {
              
              car}
      	......
      }
      

6. Judgment of responsive data

  • isRef: checks if a value is a ref object
  • isReactive: checks if an object was reactivecreated a reactive proxy
  • isReadonly: checks if an object was readonlycreated a read-only proxy
  • isProxy: Checks if an object reactiveis readonlya proxy created by the or method

4. Advantages of Composition API

1. Problems with the Options API

In the traditional OptionsAPI, if you add or modify a requirement, you need to modify it in data, methods, and computed respectively.

2. Advantages of Composition API

We can organize our code and functions more elegantly. Let the code of related functions be organized together in a more orderly manner.

5. New components

1.Fragment

  • In Vue2: Components must have a root tag
  • In Vue3: Components can have no root tags, and multiple tags will be included in a Fragment virtual element internally
  • Benefits: Reduce label levels, reduce memory usage

2.Teleport

  • What is Teleport? -- Teleportis a technique that can move our component html structure to a specified location.

    <teleport to="移动位置">
    	<div v-if="isShow" class="mask">
    		<div class="dialog">
    			<h3>我是一个弹窗</h3>
    			<button @click="isShow = false">关闭弹窗</button>
    		</div>
    	</div>
    </teleport>
    

3.Suspense

  • Render some extra content while waiting for asynchronous components, so that the application has a better user experience

  • Steps for usage:

    • Import components asynchronously

      import {
              
              defineAsyncComponent} from 'vue'
      const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
      
    • Use Suspensethe package component and configure it defaultwithfallback

      <template>
      	<div class="app">
      		<h3>我是App组件</h3>
      		<Suspense>
      			<template v-slot:default>
      				<Child/>
      			</template>
      			<template v-slot:fallback>
      				<h3>加载中.....</h3>
      			</template>
      		</Suspense>
      	</div>
      </template>
      

6. Others

1. Transfer of global API

  • Vue 2.x has many global APIs and configurations.

    • For example: registering global components, registering global directives, etc.

      //注册全局组件
      Vue.component('MyButton', {
              
              
        data: () => ({
              
              
          count: 0
        }),
        template: '<button @click="count++">Clicked {
              
              { count }} times.</button>'
      })
      
      //注册全局指令
      Vue.directive('focus', {
              
              
        inserted: el => el.focus()
      }
      
  • These APIs have been adjusted in Vue3.0:

    • Adjust the global API, ie: Vue.xxxto the application instance ( app)

      2.x Global API ( Vue) 3.x instance API ( app)
      Vue.config.xxxx app.config.xxxx
      Vue.config.productionTip remove
      Vue.component app.component
      Directive.view app.directive
      Vue.mixin app.mixin
      Vue.use app.use
      Vue.prototype app.config.globalProperties

2. Other changes

  • The data option should always be declared as a function.

  • Excessive class name changes:

    • Vue2.x writing method

      .v-enter,
      .v-leave-to {
              
              
        opacity: 0;
      }
      .v-leave,
      .v-enter-to {
              
              
        opacity: 1;
      }
      
    • Vue3.x writing method

      .v-enter-from,
      .v-leave-to {
              
              
        opacity: 0;
      }
      
      .v-leave-from,
      .v-enter-to {
              
              
        opacity: 1;
      }
      
  • Remove keyCode as a v-on modifier, and no longer supportconfig.keyCodes

  • removev-on.native modifier

    • Bind event in parent component

      <my-component
        v-on:close="handleComponentEvent"
        v-on:click="handleNativeClickEvent"
      />
      
    • Declare custom events in subcomponents

      <script>
        export default {
          emits: ['close']
        }
      </script>
      
  • remove filter

    Filters While this seems convenient, it requires a custom syntax that breaks the assumption that expressions inside curly braces are "just JavaScript", which has not only a learning cost, but an implementation cost as well! It is recommended to replace filters with method calls or computed properties.

Finally, taking the technical route is doomed to keep learning. A front-end learning route is attached!

insert image description here

Guess you like

Origin blog.csdn.net/qq_45496282/article/details/125948423