Quick start vue3

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

This article is the notes I made before learning Vue3, plus some supplements from the official website and other places. Through this article, you can quickly understand the new features of Vue3.

1. How to create Vue3

Before creating a vue3 project, you can learn about the new generation of front-end construction toolsQuickly, here we simply introduce
Quickly

1. Advantages of Vite

1. Advantages of ESM-based development services:

  • No need to package project source code
  • Natural on-demand loading
  • Can take advantage of file-level browser caching

2. Compilation performance optimization based on Esbuild
Please add a picture description
3. Built-in web building function, out of the box:
Please add a picture description
After understanding vite, we use vite to create projects. If you want to know more about vite, you can go to the official website.

2. Create a vue3 project

1. Here we choose to use Vite to build the project

// npm
npm create vite@latest
//Yarn
yarn create vite
//PNPM
pnpm create vite

2. Create a template + select a template (here we choose vue + javaScript)
to continue:

 //进入项目文件夹
 cd vite-project        
 //初始化项目
  npm install             
 //运行项目
 npm run dev           

At this time, the project runs normally
insert image description here

2. Getting Started with Vue3

1. Composition API

Vue3 proposes Composition API, which can collect a logical code together and write a hook separately, and then introduce it, without splitting data and methods like in vue2.

Here is a quote from the official website :

Composition API (Composition API) is a collection of APIs that allow us to write Vue components using functions instead of declaring options
. It's an umbrella term that covers APIs that: 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 components.

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

2.setup

  1. Understanding: A new configuration item in Vue3.0, the value is a function.
  2. setup is the "stage of performance" of all Composition APIs (composition APIs).
  3. The components used in the components: data, methods, etc., must be configured in the setup.

(1). The execution sequence of
setup is executed before Create and created, and the this in it is printed as undefined

(2) Parameters accepted by setup

setup(props, context)

props: It receives the value passed by the parent component.
context: context object, used to replace the properties accessible by the previous this method

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 distributes custom events, equivalent to this.$emit.

insert image description here

(3) setup return value
setup returns an object, the data in this object can be used directly in the template, and the value returned in setup can also be obtained through this.xxx in the data configuration item
insert image description here

Three, ref function and reactive function

The data we wrote before is not responsive data. We can define responsive data through the ref function and reactive, and functions need to be introduced before use.

1. ref function

● Function: Define a responsive data
● Syntax: const xxx = ref(initValue)
○ Create a reference object (reference object, ref object for short) containing responsive data.
○ Operate data in JS: xxx.value
○ Read data in template: No need for .value, directly: <div>{ {xxx}}</div>

Remark:

The received data can be: basic type or object type.
Basic types of data: Responsiveness is still completed by the get and set of Object.defineProperty(). Object type data: internally "requests"
the new function in Vue3.0 - the reactive function. So when defining responsive data, we can directly use the reactive function

<script lang="js">
//引入ref函数
import {
    
    defineComponent,ref} from "vue";

export default defineComponent({
    
    
  name:'App',
  data(){
    
    
    return{
    
    

    }
  },
  setup(props, context){
    
    
  //定义一个响应式数据
    let num = ref(0)
    //定义方法
    function  add(){
    
    
       console.log(1)
       //在setup中要拿到ref定义的数据需要.value
       num.value++
    }
    //把数据和方法返回出去,模板中才能使用
    return {
    
    num,add}
  }
})
</script>

<template>
  <div @click="add()">{
    
    {
    
    num}}</div>
</template>

2. reactive function

● Function: Define an object type of reactive data (do not use it for basic types, use the ref function)
● Syntax: const proxy object = reactive (source object) receives an object (or array) and returns a proxy object (Proxy’s Instance object, referred to as proxy object)
● The reactive data defined by reactive is "deep level".
● The internal ES6-based Proxy implementation operates on the internal data of the source object through the proxy object.

<script lang="js">
//引入reactive
import {
    
    defineComponent,ref,reactive} from "vue";

export default defineComponent({
    
    
  name:'App',
  data(){
    
    
    return{
    
    

    }
  },
  setup(props, context){
    
    
    let objs = reactive({
    
    
       name:'ld',
       age:20
    })
    function  updata(){
    
    
    //读取reactive定义的数据的时候不需要.cvalue
       objs.age = 28
    }
    return {
    
    objs,updata}
  }
})
</script>

<template>
  <div @click="updata()">{
    
    {
    
    objs}}</div>
</template>

3. reactive vs. ref

● Comparison from the perspective of defining data:

ref: Used to define basic type data.
reactive: 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 a proxy object through reactive internally.

● Comparison from the perspective of principle:

ref implements responsiveness (data hijacking) through the get and set of Object.defineProperty().
reactive implements responsiveness (data hijacking) by using Proxy, and manipulates the data inside the source object through Reflect.

● Comparison from the perspective of use:

Data defined by ref: .value is required to operate the data, and .value is not required for direct reading in the template when reading data.
The data defined by reactive: operation data and read data: neither need .value.

4. Extension: use ref to get dom in vue3

In vue2, we can use ref to get elements. In vue3, we can do the same, but the way of using it is different.

//拿到单个DOM
<script lang="js">
import {
    
    defineComponent,ref,reactive} from "vue";
export default defineComponent({
    
    
  name:'App',
  setup(props, context){
    
    
    let item = ref(null)
    console.log(item)
    return {
    
    item}
  }
})
</script>

<template>
  <div ref="item" id="item">20</div>
</template>

//获取多个DOM

<script lang="js">
import {
    
    defineComponent,ref,nextTick} from "vue";
export default defineComponent({
    
    
  name:'App',
  setup(props, context){
    
    
    // 存储dom数组
    const myRef = ref([]);

    const setRef = (el) => {
    
    
      myRef.value.push(el);
    };
    //下一个DOM 更新周期之后执行
    nextTick(() => {
    
    
      console.dir(myRef.value);
    });

    return {
    
    setRef}
  }
})
</script>

<template>
  <div v-for="(item,index) in 3" :ref="setRef">10</div>
</template>

Get multiple ref renderings:
insert image description here

Four, computed and watch

1. computed

Consistent with the configuration method in vue2

import {
    
    defineComponent,reactive,computed} from "vue";
...
setup(){
    
    
    let pers = reactive({
    
    
        name:'dlh',
        age:38
    })
    //计算属性——简写
    let compName = computed(()=>{
    
    
      return pers.name + '-' + pers.age
    })
    //计算属性——完整
    let compNames = computed({
    
    
      //读取
      get(){
    
    
        return pers.name + '-' + pers.age
      },
      //修改
      set(value){
    
    
        const nameArr = value.split('-')
        pers.name= nameArr[0]
        pers.age = nameArr[1]
      }
    })
    return {
    
    
      compName,compNames
    }
  }

2. watch

Consistent with the configuration method in vue2

watch(data,handler,object)
data: monitored data
handler(newValue,oldValue): callback function (value after change, value before change)
object: optional configuration item { immediate: true, deep: true }

import {
    
    watch,ref,reactive} from "vue";
...
setup(){
    
    
let num=ref(5),num2=ref(10)
let person = reactive({
    
    
       name:'5465',
       age:18
}
//情况一:监视ref定义的响应式数据
watch(num,(newValue,oldValue)=>{
    
    
      console.log('num变化了',newValue,oldValue)
    },{
    
    immediate:true})
}
//情况二:监视多个ref定义的响应式数据[数组方式]
watch([num,num2],(newValue,oldValue)=>{
    
    
      console.log('num或num2变化了',newValue,oldValue)
    })
/* 
情况三:监视reactive定义的响应式数据,无法正确获得oldValue,并且强制开启了深度监视 
*/
watch(person,(newValue,oldValue)=>{
    
    
	console.log('person变化了',newValue,oldValue)
},{
    
    immediate:true)
//情况四:监视reactive定义的响应式数据中的某个属性(参数以函数返回值的形式传递)
watch(()=>person.num,(newValue,oldValue)=>{
    
    
	console.log('person的job变化了',newValue,oldValue)
},{
    
    immediate:true,deep:true}) 

//情况五:监视reactive定义的响应式数据中的多个数据[数组]
watch([()=>person.num,()=>person.age],(newValue,oldValue)=>{
    
    
	console.log('person的job变化了',newValue,oldValue)
},{
    
    immediate:true,deep:true})

3. watchEffect function

In watch, it is necessary to specify the monitored attribute and the monitored callback, but in watchEffect, it is not necessary to specify which attribute to monitor, and which attribute is used in the monitored callback, then which attribute to monitor.

//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
watchEffect(()=>{
    
    
    const num1 = sum.value
    const num2 = person.age
    console.log('watchEffect配置的回调执行了')
})

5. Life cycle

insert image description here
The life cycle needs to be imported through import and used in the setup function, and the life cycle of Vue3 is faster than that of Vue2.X.

View2.X View 3
beforeCreate setup()
created setup()
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured
onRenderTracked (new)
onRenderTriggered (new)

Added two new hooks

onRenderTriggered is called when virtual DOM re-rendering is tracked
onRenderTracked is called when virtual DOM re-rendering is triggered

Using lifecycle hooks in setup

import {
    
    defineComponent,onMounted} from "vue";
...
setup(){
    
    
    onMounted(()=>{
    
    
      console.log('Mounted !!')
    })
  }

6. Custom hook function

The hooks function in vue3 is equivalent to the mixin in vue2. The essence of hooks is a function. It is
to extract the js code of some individual functions of the file and put it in a separate js file. Its advantage is that it can be reused Code to make the logic in setup clearer and easier to understand.

Encapsulate hooks that monitor the mouse position

// src/hooks/useMove.js
import {
    
    ref} from 'vue'
export default function(){
    
    
    //创建2个响应式变量来储存用户鼠标x轴和y轴的位置
    let pageX = ref(0) , pageY = ref(0)
    window.addEventListener('mousemove',(event)=>{
    
    
        pageX.value = event.pageX
        pageY.value = event.pageY
    })
    return {
    
    
        pageX,
        pageY
    }
}
//组件中引入使用

<script setup>
import useMove from "./hooks/useMove"
const {
    
      pageX, pageY} = useMove()
</script>
 
<template>
   <div>
      X: {
    
    {
    
    pageX }} Y:{
    
    {
    
     pageY }}
   </div>
</template>
 
<style scoped>
</style>

Eight, provide and inject

They implement communication between ancestor and descendant components

Parent components have a provide option to provide data and descendant components have an inject option to start consuming this data

//祖组件
import {
    
    defineComponent, provide, reactive} from "vue";
...
setup(){
    
    
    let hobby = reactive({
    
    name:'爱好',price:'无价'})
    provide('hobby',hobby)
  }
//后代组件
import {
    
    inject, ref} from 'vue'
...
setup(){
    
    
	const hobby = inject('hobby')
	return{
    
    
	   hobby
	}
}

9. Teleport - any portal

Specific html templates can be delivered anywhere in the Dom

Teleport has one required property - to to requires prop, must be a valid query selector or HTMLElement

 <teleport to='#portal'>
      <div v-if="isShow" class='doms'>
        Hello ! teleport
     </div>
</teleport>

Next, write a case to clearly know its usage.
First find the index.html file

//在</body>前面添加<div id='portal'></div>
  <body>
    <div id="app"></div>
    <div id='portal'></div>
    <script type="module" src="/src/main.js"></script>
  </body>

in the child component

<script lang="js">
import {
    
     ref } from 'vue'
export default {
    
    
  setup () {
    
    
    //控制隐藏的变量
    const isShow = ref(false)
    //定时器id
    let closeTime = null;
    //当用户点击弹出
    const showNotification = () => {
    
    
      isShow.value = true
      clearTimeout(closeTime)
      closeTime = setTimeout(() => {
    
    
        isShow.value = false
      }, 2000)
    }
    return {
    
    
      isShow,
      showNotification
    }
  }
}
</script>

<template>
  <div class='portals'>
    <button @click='showNotification'> 显示 </button>
    //需要传送的内容写在teleport里面并且to的地址为前面index文件中的id
 
    <teleport to='#portal'>
      <div v-if="isShow" class='doms'>
        Hello ! teleport
      </div>
    </teleport>
  </div>
</template>

<style scoped>
.doms {
    
    
  position: fixed;
  bottom: 20px;
  left: 20px;
  width: 120px;
  padding: 30px;
  color: #1a1a1a;
  background-color: #fff;
  border-radius: 10px;
}
</style>

Final time effect: When the user clicks, a prompt box appears on the lower left, and disappears after 2 seconds
insert image description here

10. Judgment of Responsive Data

  1. isRef: checks if a value is a ref object
  2. isReactive: checks if an object is a reactive proxy created by reactive
  3. isReadonly: checks if an object is a readonly proxy created by readonly
  4. isProxy: checks if an object is a proxy created by the eactive or readonly method

11. Some other Composition APIs

1. toRaw and markRaw

toRaw:

Function: Convert a reactive object generated by reactive 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.


import {
    
    defineComponent,reactive,toRaw} from "vue";
export default defineComponent({
    
    
  setup(){
    
    
    let obj = reactive({
    
    
      name:'段',
      age:20
    })
    let objToRaw =  toRaw(obj)
    console.log(obj,objToRaw)
    return{
    
    
      obj,
      objToRaw
    }
  }
})

At this time, the second data becomes ordinary data.
insert image description here

markRaw:

Role: Mark an object so that it will never become a responsive object again.
Application scenarios:
1. Some values ​​should not be set as responsive, such as complex third-party libraries.
2. When rendering large lists with immutable data sources, skipping reactive transformations can improve performance.

2.shallowReactive 与 shallowRef

shallowReactive : only handles the responsiveness of the outermost properties in the object (that is, the shallow responsiveness)

Usage scenario: If there is an object structure with multiple layers of nesting, our requirement is only to modify the outermost data, so we don’t need to convert all the nested structures inside to responsive, we only need to set the outermost attribute to responsive This can improve performance.

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

Usage scenario: If there is an object data, the subsequent function will not modify the properties in the object, but generate a new object to replace it, then you can use it

3.readonly 和 shallowReadonly

readonly : Make a reactive data read-only (deep read-only).

Each attribute of the inner layer is set to read-only, and an error will be reported if the modification operation is performed.

shallowReadonly: Make a responsive data read-only (shallow read-only).

If it is shallow, it only targets the outermost layer, and no error will be reported when modifying the inner layer

Application scenario: use when the data does not want to be modified, choose api according to different degrees

12. Changes in the global API

There are many global APIs and configurations in Vue 2, and some adjustments have been made to these APIs in Vue3:

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

For example, mount $api to the prototype

import {
    
     createApp } from 'vue'
import './style.css'
import App from './App.vue'
import API from '@/api/api';

const app =  createApp(App)
app.config.globalProperties.$API = API;
app.mount('#app')

Summarize

The above is what I want to talk about today. This article only briefly introduces some features in vue3. For more knowledge, you can go to the official document. I hope this note can help you.

Guess you like

Origin blog.csdn.net/m0_63831957/article/details/129772843