Vue3 starts

1. Introduction to Vue3

1.1. [Performance improvement]

  • Pack size reduced41%.

  • Initial rendering is fast55%, update rendering is fast133%.

  • Memory reduced54%.

1.2.【Source code upgrade】

  • UseProxyAlternativedefinePropertyRealistic expression.

  • duplicate fictionDOMrealistic realizationTree-Shaking.

1.3. [Embrace TypeScript]

  • Vue3can be better supportedTypeScript.

1.4. [New Features]

  1. Composition API(combinationAPI):

    • setup

    • refandreactive

    • computedandwatch

  2. New built-in components:

    • Fragment

    • Teleport

    • Suspense

  3. Other changes:

    • New lifecycle hooks

    • dataOptions should always be declared as a function

    • Removal keyCodeSupport work v-on Modification mark

2. Create Vue3 project

2.1. [Created based on vue-cli]

Click to viewOfficial Documents

Note: Currentlyvue-cli is in maintenance mode, and it is officially recommended to create projects based on Vite.

## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version

## 安装或者升级你的@vue/cli 
npm install -g @vue/cli

## 执行创建命令
vue create vue_test

##  随后选择3.x
##  Choose a version of Vue.js that you want to start the project with (Use arrow keys)
##  > 3.x
##    2.x

## 启动
cd vue_test
npm run serve

2.2. [Created based on vite] (recommended)

vite is a new generation of front-end construction tools, official website address: https://vitejs.cn, vite The advantages are as follows:

  • Lightweight and fast hot reloading (HMR) can achieve extremely fast service startup.
  • TypeScript, JSX, CSS etc. support opening box ready for use.
  • True on-demand compilation, no longer waiting for the entire application to be compiled.
  • webpackThe comparison chart between construction and vite construction is as follows:
    Insert image description here
    Insert image description here
## 1.创建命令
npm create vue@latest

## 2.具体配置
## 配置项目名称
√ Project name: vue3_test
## 是否添加TypeScript支持
√ Add TypeScript?  Yes
## 是否添加JSX支持
√ Add JSX Support?  No
## 是否添加路由环境
√ Add Vue Router for Single Page Application development?  No
## 是否添加pinia环境
√ Add Pinia for state management?  No
## 是否添加单元测试
√ Add Vitest for Unit Testing?  No
## 是否添加端到端测试方案
√ Add an End-to-End Testing Solution? » No
## 是否添加ESLint语法检查
√ Add ESLint for code quality?  Yes
## 是否添加Prettiert代码格式化
√ Add Prettier for code formatting?  No

Write one yourselfAppComponent

<template>
  <div class="app">
    <h1>你好啊!</h1>
  </div>
</template>

<script lang="ts">
  export default {
    name:'App' //组件名
  }
</script>

Install the officially recommendedvscodeplug-in:

Insert image description here

Insert image description here

Summarize:

  • ViteIn the project, index.html is the entry file of the project, which is at the outermost level of the project.
  • additionindex.htmlafter, Vite analysis <script type="module" src="xxx"> directionalJavaScript.
  • Vue3In **, an application instance is created through the **createApp function.

2.3. [A simple effect]

Vue3Backwards compatible withVue2 syntax, and templates in Vue3 do not need root tags

<template>
  <div class="person">
    <h2>姓名:{
   
   {name}}</h2>
    <h2>年龄:{
   
   {age}}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">年龄+1</button>
    <button @click="showTel">点我查看联系方式</button>
  </div>
</template>

<script lang="ts">
  export default {
    name:'App',
    data() {
      return {
        name:'张三',
        age:18,
        tel:'13888888888'
      }
    },
    methods:{
      changeName(){
        this.name = 'zhang-san'
      },
      changeAge(){
        this.age += 1
      },
      showTel(){
        alert(this.tel)
      }
    },
  }
</script>

3. Vue3 core syntax

3.1. [OptionsAPI and CompositionAPI]

  • Vue2'sAPI design is in theOptions (configuration) style.
  • Vue3’sAPI design is in theComposition (combination) style.

Disadvantages of Options API

Options typeAPI, data, methods, calculated attributes, etc. are scattered in: data, methods, < In /span>, , computed, if you want to add or modify a requirement, you need to modify it separately: datamethodscomputed

Insert image description here
Insert image description here

Advantages of Composition API

You can use functions to organize code more elegantly, so that codes for related functions can be organized together in a more orderly manner.

Insert image description here
Insert image description here

Note: The original author of the above four animated pictures: Dashuao Laoyuan

3.2. [The setup that kicks off]

setup overview

setup is a new configuration item in Vue3, and the value is a function, which is the Composition API "performance stage, the data, methods, calculated properties, monitoring, etc. used in the component are all configured in setup.

Features are as follows:

  • setupThe contents of the object returned by the function can be used directly in the template.
  • setup中访问thisundefined.
  • setupThe function will be called before beforeCreate, which is "preceded" by all hook executions.
<template>
  <div class="person">
    <h2>姓名:{
   
   {name}}</h2>
    <h2>年龄:{
   
   {age}}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">年龄+1</button>
    <button @click="showTel">点我查看联系方式</button>
  </div>
</template>

<script lang="ts">
  export default {
    name:'Person',
    setup(){
      // 数据,原来写在data中(注意:此时的name、age、tel数据都不是响应式数据)
      let name = '张三'
      let age = 18
      let tel = '13888888888'

      // 方法,原来写在methods中
      function changeName(){
        name = 'zhang-san' //注意:此时这么修改name页面是不变化的
        console.log(name)
      }
      function changeAge(){
        age += 1 //注意:此时这么修改age页面是不变化的
        console.log(age)
      }
      function showTel(){
        alert(tel)
      }

      // 返回一个对象,对象中的内容,模板中可以直接使用
      return {name,age,tel,changeName,changeAge,showTel}
    }
  }
</script>

Return value of setup

  • If anobject is returned: then the properties, methods, etc. in the object can be used directly in the template** (focus on ). **
  • If it returns afunction: you can customize the rendering content, the code is as follows:
setup(){
  return ()=> '你好啊!'
}

The relationship between setup and OptionsAPI

  • Vue2 in the configuration of …) >Attributes and methods in. data, (methos setup
  • However,setupinnot availableVue2placement (data ,methos…).
  • If conflicts with Vue2, setup takes precedence.

setup syntactic sugar

setupThe function has a syntactic sugar. This syntactic sugar allows us to separate setup. The code is as follows:

<template>
  <div class="person">
    <h2>姓名:{
   
   {name}}</h2>
    <h2>年龄:{
   
   {age}}</h2>
    <button @click="changName">修改名字</button>
    <button @click="changAge">年龄+1</button>
    <button @click="showTel">点我查看联系方式</button>
  </div>
</template>

<script lang="ts">
  export default {
    name:'Person',
  }
</script>

<!-- 下面的写法是setup语法糖 -->
<script setup lang="ts">
  console.log(this) //undefined
  
  // 数据(注意:此时的name、age、tel都不是响应式数据)
  let name = '张三'
  let age = 18
  let tel = '13888888888'
	
  // 方法
  function changName(){
    name = 'zhang-san'//注意:此时这么修改name页面是不变化的
  }
  function changAge(){
    console.log(age)
    age += 1 //注意:此时这么修改age页面是不变化的
  }
  function showTel(){
    alert(tel)
  }
</script>

extension: In the above code, you also need to write a tag without writing setup to specify the component name, which is troublesome. We can use a>Plugin simplification in scriptvite

  1. first step:npm i vite-plugin-vue-setup-extend -D
  2. Step two:vite.config.ts
import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

export default defineConfig({
  plugins: [ VueSetupExtend() ]
})
  1. third step:<script setup lang="ts" name="Person">

3.3. [ref creation: basic type of responsive data]

  • **Function:**Define responsive variables.
  • Language:let xxx = ref(初始值).
  • **Return value: **An instance object of RefImpl, referred to as ref对象 or ref, . properties are responsiverefObject'svalue
  • important point:
    • JSThe operation data in requires: xxx.value, but .value is not required in the template, you can use it directly.
    • For let name = ref('张三'), name is not responsive, and name.value is responsive.
<template>
  <div class="person">
    <h2>姓名:{
   
   {name}}</h2>
    <h2>年龄:{
   
   {age}}</h2>
    <h2>地址:{
   
   {address}}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">年龄+1</button>
    <button @click="showTel">点我查看联系方式</button>
  </div>
</template>

<script setup lang="ts" name="Person">
  import {ref} from 'vue'
  
  // name和age是一个RefImpl的实例对象,简称ref对象,它们的value属性是响应式的。
  let name = ref('张三')
  let age = ref(18)
  // tel、address就是一个普通的字符串,不是响应式的
  let tel = '13888888888'
  let address = '北京昌平区宏福苑·宏福科技园'

  function changeName(){
    // JS中操作ref对象时候需要.value
    name.value = '李四'
    console.log(name.value)
  }
  function changeAge(){
    // JS中操作ref对象时候需要.value
    age.value += 1 
    console.log(age.value)
  }
  function showTel(){
    alert(tel)
  }
</script>

Guess you like

Origin blog.csdn.net/qq_37215621/article/details/133907564