[Vue3 Knowledge Lecture 2] Vue3 new features, vue-devtools debugging tool, scaffolding construction

1. New features of Vue3

1.1 Rewrite two-way data binding

1.1.1 Vue2 is implemented based on Object.defineProperty()

Digital management platform
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
permission system-Mall
personal blog address

Simplify the core method defineReactive in Vue as follows:

function defineReactive (obj, key, val, cb) {
    var dep = new Dep();
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: ()=>{
            /*....依赖收集等....*/
            dep.depend()
            return val
        },
        set:newVal=> {
            val = newVal;
            /*触发回调*/
            dep.notify()
        }
    })
}

Vue uses the defineReactive method to monitor each property of the object that needs to be observed. The dep object is equivalent to a dispatch center. If there is data that uses this attribute, it will automatically collect the attribute to the dispatch center. If a certain attribute changes, the dispatch center will be notified to update the view.

1.1.2 Vue3 based on Proxy implementation

let proxyObj = new Proxy(obj,{
    get : function (target,prop) {
        return prop in target ? target[prop] : 0
    },
    set : function (target,prop,value) {
        target[prop] = 888;
    }
})

Proxy has the following advantages compared with the Object.defineProperty(obj, prop, desc) method:

  • Lose those troublesome backup data**
  • omit the for in loop
  • Can monitor array changes
    • The code is more simplified
  • Can monitor dynamically added attributes
  • Can monitor deleted properties
  • You can monitor the index and length properties of the array

1.2 Optimizing Virtual DOM

In Vue2, every time the diff is updated, it is compared in full, while Vue3 only compares the marked ones, which greatly reduces the comparison consumption of non-dynamic content.

Vue Template Explorer we can see the static markup through this website
Insert image description here

  • patch flag optimizes static trees

    <span>Hello world!</span>
    <span>Hello world!</span>
    <span>Hello world!</span>
    <span>Hello world!</span>
    <span>{
         
         {msg}}</span>
    <span>Hello world!</span>
    <span>Hello world! </span>```
    
  • Vue3The compiled one Vdomlooks like this

    export function render(_ctx,_cache,$props,$setup,$data,$options){return (_openBlock(),_createBlock(_Fragment,null,[
    _createvNode( "span", null,"Hello world ! "),
    _createvNode( "span",null,"Hello world! "),
    _createvNode( "span",null,"Hello world! "),
    _createvNode( "span", null,"Hello world! "),
    _createVNode("span", null,_toDisplaystring(_ctx.msg),1/* TEXT */),
    _createvNode( "span", null,"Hello world! "),
    _createvNode( "span", null,"Hello world! ")],64/*STABLE_FRAGMENT */))
    
  • Added patch flag tag

    TEXT = 1 // 动态文本节点
    CLASS=1<<1,1 // 2//动态class
    STYLE=1<<2,// 4 //动态style
    PROPS=1<<3,// 8 //动态属性,但不包含类名和样式
    FULLPR0PS=1<<4,// 16 //具有动态key属性,当key改变时,需要进行完整的diff比较。
    HYDRATE_ EVENTS = 1 << 5,// 32 //带有监听事件的节点
    STABLE FRAGMENT = 1 << 6, // 64 //一个不会改变子节点顺序的fragment
    KEYED_ FRAGMENT = 1 << 7, // 128 //带有key属性的fragment 或部分子字节有key
    UNKEYED FRAGMENT = 1<< 8, // 256 //子节点没有key 的fragment
    NEED PATCH = 1 << 9, // 512 //一个节点只会进行非props比较
    DYNAMIC_SLOTS = 1 << 10 // 1024 // 动态slot
    HOISTED = -1 // 静态节点
    BALL = -2
    

We found that when creating a dynamic dom element, Vdom not only simulates its basic information, but also adds a mark to it: 1 /* TEXT */. This mark is called the patch flag. The power of patch flag is that when your diff algorithm reaches the _createBlock function, it will ignore all static nodes and only compare marked dynamic nodes, and it is still valid under multiple levels of nesting. Although JavaScript comparison of Vdom is already very fast, the emergence of patch flag has greatly improved the performance of Vdom in Vue3, especially when targeting large components.

1.3 Fragments

  • vue3 allows us to support multiple root nodes

    <div>Hello World</div>
    <div>Hello Vue</div>
    <div :key="index" v-for="item,index in [10,20,304]">{
         
         {item}}</div>
    
  • Also supports render JSX writing method

    render() {
        return (
            <>
                {this.visable ? (
                    <div>{this.obj.name}</div>
                ) : (
                    <div>{this.obj.price}</div>
                )}
                <input v-model={this.val}></input>
                {[1, 2, 3].map((v) => {
                   return <div>{v}-----</div>;
                })}
            </>
        );
    },
    
  • Also added Suspense teleport and multi-v-model usage

1.4 Tree shaking

To put it simply, it is to remove useless code while keeping the code running results unchanged.

In Vue2, no matter what features we use, they end up in production code. The main reason is that the Vue instance is a singleton in the project, and the bundler cannot detect which properties of the object are used in the code. The Vue3 source code introduces the tree shaking feature to divide the global API into chunks. If you don't use some of its features, they won't be included in your base package. For example, if you want to use watch, just import {watch} from 'vue'. Other computed components will not be packaged and reduced in size if they are not used.

1.5 Composition API

The Composition API is a collection of APIs that allow us to write Vue components using functions instead of declaring options. It is an umbrella term that covers APIs for:

Reactive APIs: such as ref() and reactive(), allow us to directly create reactive state, computed properties and listeners.

Lifecycle hooks: such as onMounted() and onUnmounted(), allow us to add logic at various lifecycle stages of the component.

Dependency injection: For example, provide() and inject() allow us to take advantage of Vue's dependency injection system when using reactive APIs.

The composition API is a built-in feature of Vue 3 and Vue 2.7. For older Vue 2 versions, you can use the officially maintained plug-in @vue/composition-api. In Vue 3, the combined API basically matches

<script setup>
	import { ref, onMounted } from 'vue'
	
	// 响应式状态
	const count = ref(0)
	
	// 更改状态、触发更新的函数
	function increment() {
	  count.value++
	}
	
	// 生命周期钩子
	onMounted(() => {
	  console.log(`计数器初始值为 ${count.value}。`)
	})
</script>

<template>
  <button @click="increment">点击了:{
   
   { count }} 次</button>
</template>

Using composite APIs has the following advantages:

  • Better logic reuse
    The most basic advantage of the combined API is that it allows us to achieve more concise and efficient logic reuse by combining functions. In the optional API, our main logic reuse mechanism is mixins, and the combined API solves all the shortcomings of mixins.
    The logic reuse capabilities provided by the composition API have spawned some great community projects, such as VueUse , a growing collection of tool-based composition functions.
  • More flexible code organization:
    Code related to the same logical concern is grouped together: we no longer need to scroll back and forth between different option blocks for a logical concern. In addition, we can now easily move this set of code to an external file, no longer needing to reorganize the code for abstraction, greatly reducing the cost of refactoring, which is very critical in large projects with long-term maintenance.
  • Better type inference
    The compositional API mainly utilizes basic variables and functions, which are inherently type-friendly. Code rewritten with the compositional API can enjoy complete type inference without writing too many type annotations. Most of the time, composable API code written in TypeScript is not much different than written in JavaScript!
  • The smaller production package size
    combined with <script setup> the use of the combined API is more efficient than the equivalent optional API and is also more friendly to code compression. This is because <script setup> the component template written in the form is compiled into an inline function and <script setup> is in the same scope as the code in . Unlike the optional API, which relies on the this context object to access properties, compiled templates can directly access <script setup> variables defined in , without the need to proxy from the instance. This is more friendly to code compression, because local variable names can be compressed, but object property names cannot.

2. vue-devtools debugging tool

The vue-devtools debugging tool officially provided by vue can facilitate developers to debug and develop vue projects. Chrome browser installs vue-devtools online

  • vue 2.x debugging tool

    https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd

  • vue 3.x debugging tool

    https://chrome.google.com/webstore/detail/vuejs-devtools/ljjemllljcmogpfapbkkighbhhppjdbg

Note: The browser debugging tools of vue2 and vue3 cannot be used cross-wise!

Click [External link image transfer failed in the upper right corner of the Chrome browser. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-clRSTwtM-1672016260783) (Vue3 course notes introduction.assets/image-20221225220407446.png )] button, select More Tools->Extensions->Vue.js devtools details, and check the following two options:
Insert image description here

Note: After modifying the configuration items, you must restart the browser to take effect!

Visit a page using vue in the browser, open the browser's developer tools, switch to the Vue panel, and use vue-devtools to debug the current page.
Insert image description here

3. Environment configuration

  1. Development environment : Vite3+ Vue3

    • Compatibility: Vite requires Node.js version 14.18+, 16+. However, some templates require a higher Node version to run properly. When your package manager issues a warning, please upgrade your Node version.
    • Vue3 adopts composition API
  2. Officially recommended IDE configuration : Visual Studio Code

  3. Vite builds scaffolding :

    Execute the following command to initialize the project

    npm init vue@latest
    

    This command will install and execute create-vue , which is Vue's official project scaffolding tool. You'll see hints of optional features like TypeScript and testing support:

    ✔ Project name: … <your-project-name>
    ✔ Add TypeScript? … No / Yes
    ✔ Add JSX Support? … No / Yes
    ✔ Add Vue Router for Single Page Application development? … No / Yes
    ✔ Add Pinia for state management? … No / Yes
    ✔ Add Vitest for Unit testing? … No / Yes
    ✔ Add Cypress for both Unit and End-to-End testing? … No / Yes
    ✔ Add ESLint for code quality? … No / Yes
    ✔ Add Prettier for code formatting? … No / Yes
    
    Scaffolding project in ./<your-project-name>...
    Done.
    

    If you are not sure whether you want to enable a certain function, you can directly press the Enter key to select it No. After the project is created, install the dependencies and start the development server by following these steps:

    cd <your-project-name>
    npm install
    npm run dev
    

    Note: You can also use vite official commands to configure the vue project:

    npm init vite@latest
    # or
    npm create vite@latest
    

    Install the sass preprocessing language:

    npm install --save-dev sass
    

4. Introduction to scaffolding catalog

  • The ones below public will not be compiled and can store static resources.
  • Compilable static resources can be stored under assets
  • components are used to store our components below
  • router stores routing related files
  • stores stores state management related files
  • App.vue is a global component
  • main.js global js file
  • index.html is a very important entry file (Vite’s entry file is an html file. It will not compile these js files at first. Only when you use it, such as script src="xxxxx.js" will initiate a request and be intercepted by vite. Only then will the js file be parsed)
  • vite.config.js This is the configuration file of vite. The specific configuration items will be explained in detail later.

5. SFC syntax specification analysis

*.vue Files are composed of three types of top-level syntax blocks: <template>, <script>,<style>

  • <template>
    • Each *.vuefile can contain at most one top-level <template>block at a time.
    • The contents are extracted and passed to the render function, @vue/compiler-domwhich is precompiled JavaScript and attached to the exported component as its renderoptions.
  • <script>
    • Each *.vuefile can have multiple <script>blocks (exclusive <script setup>)
    • The script will be ES Moduleexecuted as .
    • The default exported content should be the Vue component options object, which is either an ordinary object or the return value of defineComponent.
  • <script setup>
    • Each *.vue file can only have at most one <script setup>block (excluding regular ones <script>)
    • The script will be preprocessed and setup()used as a function of the component, which means it will be executed in each component instance. <script setup>The top-level binding is automatically exposed to the template. See <script setup>the documentation for more details.
  • <style>
    • A *.vuefile can contain multiple <style>tags.
    • <style>Tags can encapsulate styles within the current component via scopedor (see SFC Style Properties for more details). module attributeTags with different packaging modes <style>can be mixed in the same component.

Appendix: It is recommended to adopt the domestic Taobao mirroring strategy

Install Taobao mirror globally

npm install -g cnpm --registry=https://registry.npm.taobao.org 

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/132619988