The most detailed introduction to the use of Vue3 on the entire network

1. Introduction to Vue3

1. Performance improvement

  • Pack size reduced by 41%
  • Initial rendering is 55% faster, update rendering is 133% faster
  • Memory reduced by 54%

2. Source code upgrade

  • Use Proxy instead of defineProperty to implement responsiveness
  • Rewriting the implementation of virtual DOM and Tree-Shaking

3. Have TypeScript

  • Vue3 can better support TypeScript

4.New special new

  • Composition API(组合API)
    – Setup配置
    – ref与reactive
    – watch与watchEffect
    – provide与inject

  • New built-in components
    – Fragment
    – Teleport
    – Suspense

  • Other changes
    – New lifecycle hooks
    – data option should always be declared as a function
    – Removed keyCode support as a modifier for v-on

5. Combined API and configuration item API

  • Problems with the Options API
    – Using the traditional OptionsAPI, if you add or modify a requirement, you need to modify it in data, methods, and computed respectively.

  • Advantages of Composition API
    – We can organize our code and functions more elegantly. Let the codes of related functions be organized together in a more orderly manner.

2. Vue3 project creation

  1. Vue-cli cheap Vue3
vue create 名称		// 选择需要的配置 到版本选择3.X即可	
npm run server		// 运行服务器

Insert image description here

  1. Vite creates Vue3
npm init vue@latest		// 根据自己的需求选择功能
npm install				// 注意这个方式创建是没有node_modules的
npm run dev				// 运行服务器

Insert image description here

  1. Vite creates Vue (method 2)
npm init vite-app 项目名称 	// 默认功能是全不选的
npm install 				// 安装 依赖
npm run dev					// 运行服务

Insert image description here

3. Setup

There is a new Setup configuration item function in Vue3. Function variables are defined in it and must be returned before they can be used in the template.

<template>
  <div>
    <h1> APP Setup</h1>
    <h3>我是{
    
    {
    
    name}}</h3>
    <h3>今年{
    
    {
    
    age}}</h3>
    <button @click="leftClick">点我看帅哥</button>
    <button @click="addAge">点我年龄+1</button>
  </div>
  <router-view/>
</template>

<script>
export default{
    
                       // Vue3中所有的变量 函数编写 都写在Setup函数中
  setup(){
    
    
    // console.log(this.name)       // Vue3中没有This 
    let name = 'Like'
    let age = 20

    function leftClick() {
    
    
      alert('帅哥!!')
    }

    let addAge = () => {
    
    
      console.log('开始加啦!')
      age++                       // 发现问题 渲染没有问题 但是没有响应式 页面底层变了 变量没变
      console.log(age)
    }

    return {
    
                        // 函数 变量 都需要返回 
      age, name, leftClick, addAge
    }
  }
}
</script>

4. ref and reactive


Using Ref and Reactive requires importing

import {
    
    ref, reactive} from "vue";

Basic data type (array string Boolean) If you want to add responsiveness, you can directly use the Ref package to modify it through the variable name.Value
Object array is needed if you want to add responsiveness Use Reactive wrapping to modify through variables and properties

<template>
  <div>
    <h1> APP Setup</h1>
    <h3>我是{
    
    {
    
    name.name}}</h3>    <!-- reactive的用法 -->
    <h3>今年{
    
    {
    
    age}}</h3>      	  <!-- ref 的用法 -->
    <button @click="leftClick">点我看帅哥</button>
    <button @click="addAge">点我年龄+1</button>
  </div>
  <router-view/>
</template>

<script>

import {
    
    ref, reactive} from "vue";

export default{
    
                      
  setup(){
    
    
    // console.log(this.name)       // Vue3中没有This
    let name = reactive({
    
    name:'like', height:180})      // 需要放在一个对象里面
    let age = ref(20)

    function leftClick() {
    
    
      name.name = name.name + '?'
      console.log(name)           // 这个时候我们可以看到name是一个Proxy对象 可以通过名称直接拿值
    }

    let addAge = () => {
    
    
      console.log('开始加啦!', age)   // 这个时候我们打印age发现是一个RefImpl对象 中有一个Value就是我们的数据值
      age.value = age.value+1                      // 发现问题 渲染没有问题 但是没有响应式 页面底层变了 变量没变
      console.log(age.value)
    }

    return {
    
                        // 函数 变量 都需要返回
      age, name, leftClick, addAge,
    }
  }
}
</script>

Insert image description here

五、setup-context

The function of context is to receive parameters. Custom attributes accepted by context internal function props.

组件 
	<template>
	<div>
	  <h1>我是home组件{
    
    {
    
    name}}</h1>
	</div>
	</template>
	
	<script>
	export default {
    
    
	  name: 'HomeView',
	  props:['name'],
	  setup(context){
    
    
	    console.log(context)
	  }
	}
	</script>


App.vue
	<template>
  <div>
    <h1> Context</h1>
    <HomeView name="like"></HomeView>
  </div>
</template>

<script lang="js" setup>    // 语言可以切换成 Ts


import HomeView from './views/HomeView.vue'

export default{
    
    
  components:{
    
    HomeView},
}
</script>

Insert image description here

6. Calculated properties

Consistent with the computed configuration function in Vue2 (case: when the names change, others will also change)

<template>
  <p>姓:<input type="text" v-model="person.firstName"></p>
  <p>名:<input type="text" v-model="person.lastName"></p>
  <p>全名:{
    
    {
    
     person.fullName }}</p>
  <p>全名修改:<input type="text" v-model="person.fullName"></p>

</template>

<script>

import {
    
    ref, reactive} from 'vue'
import {
    
    computed} from 'vue'

export default {
    
    
  name: 'App',
  setup() {
    
    
    const person = reactive({
    
    
      firstName: '梅',
      lastName: '星星'
    })

    // let fullName = computed(() => {
    
    
      // return person.firstName + '-' + person.lastName
    })
    // 或者,传入箭头函数
    // person.fullName=computed(() => {
    
    
      // return person.firstName + '-' + person.lastName
    })
    // 修改,传入配置项目
    person.fullName = computed({
    
    
      get() {
    
    
        return person.firstName + '-' + person.lastName
      },
      set(value) {
    
    
        const nameArr = value.split('-')
        person.firstName = nameArr[0]
        person.lastName = nameArr[1]
      }
    })
    return {
    
    person}
  },
}
</script>

Insert image description here

7. Monitoring attributes

<template>
  <h2>年龄是:{
    
    {
    
     age }}</h2>
  <button @click="age++">点我年龄增加</button>
  <hr>
  <h2>姓名是:{
    
    {
    
     person.name }}</h2>
  <button @click="person.name+='?'">点我姓名变化</button>
  <hr>
  <h2>sum是:{
    
    {
    
     sum }},msg是:{
    
    {
    
     msg }}</h2>
  <button @click="sum++">点我sum变化</button>
  |
  <button @click="msg+='?'">点我msg变化</button>

</template>

<script>

import {
    
    ref, reactive} from 'vue'
import {
    
    watch} from 'vue'

export default {
    
    
  name: 'App',
  setup() {
    
    
    const age = ref(19)
    const person = reactive({
    
    
      name: 'Like',
      age: 20
    })
    //1 监听普通
    watch(age, (newValue, oldValue) => {
    
    
      console.log('sum变化了', newValue, oldValue)
    })
    // 2 监听对象
    watch(() => person.name, (newValue, oldValue) => {
    
    
      console.log('person.name变化了', newValue, oldValue)
    })
    // 3 监听多个
    const sum = ref(100)
    const msg = ref('很好')

    watch([sum, msg], (newValue, oldValue) => {
    
    
      console.log('sum或msg变化了', newValue, oldValue)
    })
    return {
    
    person, age, sum, msg}
  },
}
</script>

Insert image description here

8. Vue3 life cycle


The life cycle hooks in Vue2.x can continue to be used in Vue3.0, but two of them have been renamed:

  • beforeDestroy is renamed to beforeUnmount
  • destroyed was renamed to unmounted

Vue3.0 also provides life cycle hooks in the form of Composition API. 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
    Insert image description here

9. Custom hook function

What is a hook?

It is essentially a function that encapsulates the Composition API used in the setup function, similar to the mixin in vue2.x. The advantages of custom hooks: reuse code, making the logic in the setup clearer and easier to understand.

RBI function example

<template>
  <h2>点击的x坐标:{
    
    {
    
     point.x }},y坐标:{
    
    {
    
     point.y }}</h2>
</template>

<script>
import {
    
    reactive} from 'vue'
import {
    
    onMounted, onBeforeUnmount} from 'vue'

export default {
    
    
  name: 'Point',
  setup() {
    
    
    const point = reactive({
    
    
      x: 0,
      y: 0
    })

    function getPoint(event) {
    
    
      console.log('X轴是:', event.pageX)
      console.log('Y轴是:', event.pageY)
      point.x = event.pageX
      point.y = event.pageY
    }

    // 挂在完成开始执行
    onMounted(() => {
    
    
      window.addEventListener('click', getPoint)
    })
    // 接除挂载时执行
    onBeforeUnmount(() => {
    
    
      console.log('sss')
      window.removeEventListener('click', getPoint)
    })
    return {
    
    point}
  },
}
</script>
<template>
  <div>
    <button @click="isShow=!isShow">点我显示隐藏</button>
    <Point v-if="isShow"></Point>
  </div>
</template>

<script>
import {
    
    ref, reactive} from 'vue'
import Point from "./components/Point.vue";
import Demo from './components/HelloWorld.vue'

export default {
    
    
  name: 'App',
  components: {
    
    Demo, Point},
  setup() {
    
    
    const isShow = ref(true)
    return {
    
    isShow}
  },
}
</script>

Insert image description here

10. toRef

  • The role of toRef: Create a ref object whose value points to a property in another object.
  • Syntax: const name =toRef(person,'name')
  • Application: When you want to provide a certain property in the responsive object for external use alone.
  • Extension:toRefs has the same function astoRef, but can create multiple ref objects in batches, syntax:toRefs(person)
<template>
  <div>
    <h2>姓名:{
    
    {
    
     name }}</h2>
    <h2>年龄:{
    
    {
    
     age }}</h2>
    <button @click="age++">改年龄</button>| <button @click="name+='~'">改姓名</button>
  </div>
</template>

<script>

import {
    
    ref, reactive,toRefs} from 'vue'

export default {
    
    
  name: 'App',
  setup() {
    
    
    const person = reactive({
    
    
      name: 'like',
      age: 19
    })
    return {
    
    
      ...toRefs(person)   // ... 解压赋值
    }
  },
}
</script>

Insert image description here

Technical novice records the learning process. Please point out any mistakes or confusion. If this article is helpful to you, please点点赞收藏+关注Thank you for your support!!!

Guess you like

Origin blog.csdn.net/MeiJin_/article/details/127651350
Recommended