Home > Web Front-end > Vue.js > body text

Get started quickly with VUE3 and summarize common API functions!

藏色散人
Release: 2022-03-24 09:54:39
forward
1998 people have browsed it

Vue3 Introduction

  • On September 18, 2020, Vue.js released version 3.0, codename: One Piece (One Piece)
  • It took more than 2 years and 2,600 submissions , 30 RFCs, 600 PRs, 99 contributors
  • tags address on github (https://github.com/vuejs/vue-next/releases/tag/v3.0.0)

What does Vue3 bring?

Performance improvement

  • The package size is reduced by 41%
  • The initial rendering is fast 55%, update rendering is 133% faster
  • Memory reduced by 54%

Source code upgrade

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

Embrace TypeScript

  • Vue3 can better support TypeScript

New features

  • Composition API

    • setup configuration
    • ref and reactive
    • watch and watchEffect
    • provide and inject
  • New built-in components

    • Fragment
    • Teleport
    • Suspense
  • ##Other changes

      New life cycle hooks
    • The data option should always be declared as a function
    • Remove keyCode support as a modifier for v-on
Related Recommended: "

vue.js Video Tutorial"

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/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
Copy after login

2. Use vite to create

Vite official Chinese documentation: https://cn.vitejs.dev

    What is vite? The new generation of front-end construction tools
  • The advantages are as follows:
    • In the development environment, no packaging operation is required, and cold start can be quickly performed
    • Lightweight and fast hot reloading (HMR)
    • True on-demand compilation, no longer waiting for the entire application to be compiled
Comparison chart between traditional build and Vite build:


Get started quickly with VUE3 and summarize common API functions!

Get started quickly with VUE3 and summarize common API functions!

## 创建工程
npm init vite-app 

## 进入工程目录
cd 

## 安装依赖
npm install

## 运行
npm run dev
Copy after login

2. Commonly used Composition API

官方文档:https://v3.cn.vuejs.org/guide/composition-api-introduction.html
Copy after login

1. The setup that kicks off

    Understanding: A new configuration item in Vue3.0, the value is a function.
  • setup is the "stage for performance" of all Composition APIs.
  • The data, methods, etc. used in the component must be configured in the setup.
  • Two return values ​​of the setup function:
    • If an object is returned, the attributes and methods in the object can be used directly in the template. (Focus on this!)
    • If a rendering function is returned, the rendering content can be customized. (Just understand it)
  • Note:
    • Try not to mix it with Vue2.x configuration.
      • Vue2.x configuration (data, methods, computed...) can access the properties and methods in the setup.
      • But the Vue2.x configuration (data, methods, computed...) cannot be accessed in the setup.
      • If there are duplicate names, an error will be reported.
    • 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

    Function: Define a responsive data
  • Introduction:
  • import {ref} from "vue"
  • Syntax:
  • const xxx = ref(initValue)
      Create a
    • reference object containing responsive data (reference object, referred to as ref object)
    • Manipulate data in JS:
    • xxx.value
    • Read data from the template, no need for
    • .value, just

      {{xxx}}

  • Remarks:
    • The received data can be of basic type or object type
    • Basic type of data: Responsiveness still relies on
    • Object. defineProperty()’s get and set complete the
    • object type data: internally “asked for help” with a new function in Vue3.0——
    • reactiveFunction

3.reactive function

    Function: Define a
  • object Reactive data of type (do not use it for basic types, use the ref function)
  • Introduction:
  • import {reactive} from 'vue'
  • Syntax:
  • const proxy object = reactive (source object)Receive an object (or array) and return a proxy object (Proxy instance object, referred to as proxy object)
  • The responsive data defined by reactive is "deep"
  • The internal Proxy implementation is based on ES6, and the internal data of the source object is operated through the proxy object

4.Responsiveness principle in Vue3.0

Responsiveness of Vue2.x

  • 实现原理:
    • 对象类型:通过Object.defineProperty()对属性的读取、修改进行拦截(数据劫持)
    • 数组类型:通过重写更新数组的一系列方法来实现拦截(对数组的变更方法进行了包裹)
Object.defineProperty(data, 'count', {
    get() {},
    set() {}})
Copy after login
  • 存在问题:
    • 新增属性、删除属性,界面不会更新
    • 直接通过下标修改数组,界面不会自动更新

Vue3.0的响应式

  • 实现原理:
    • 通过Proxy(代理):拦截对象中任意属性的变化,包括:属性值的读写、属性的添加、属性的删除等
    • 通过Reflect(反射):对源对象的属性进行操作
    • MDN文档中描述的Proxy与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'
Copy after login

5.reactive对比ref

  • 从定义数据角度对比:
    • ref用来定义:基本类型数据
    • reactive用来定义:对象(或数组)类型数据
    • 备注:ref也可以用来定义对象(或数组)类型数据,它内部会自动通过reactive转为代理对象
  • 从原理角度对比:
    • ref通过Object.defineProperty()getset来实现响应式(数据劫持)
    • reactive通过使用Proxy来实现响应式(数据劫持),并通过Reflect操作源对象内部的数据
  • 从使用角度对比:
    • ref定义的数据:操作数据需要.value,读取数据时模板中直接读取不需要.value
    • reactive定义的数据:操作数据与读取数据均不需要.value

6.setup的两个注意点

  • setup执行的时机

    • 在beforeCreate之前执行一次,this是undefined
  • setup的参数

    • props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性
    • context:上下文对象
      • attrs(捡漏props):值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于Vue2中的this.$attrs
      • slots:收到的插槽内容,相当于Vue2中的this.$slots
      • emit:分发自定义事件的函数,相当于Vue2中的this.$emit

7.计算属性与监视

computed函数

  • 与Vue2.x中computed配置功能一致
  • 写法:
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]
        }
    })}
Copy after login

watch函数

  • 与Vue2.x中watch配置功能一致
  • 两个小“坑”:
    • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)
    • 监视reactive定义的响应式数据中某个属性时:deep配置有效
// 情况一:监视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配置有效
Copy after login

watchEffect函数

  • watch的套路是:既要指明监视的属性,也要指明监视的回调
  • watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
  • watchEffect有点像computed:
    • 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值
    • 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值
// watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调
watchEffect(() => {
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect配置的回调执行了')
})
Copy after login

8.生命周期

Get started quickly with VUE3 and summarize common API functions!:
Get started quickly with VUE3 and summarize common API functions!
Vue3.0的生命周期:
Get started quickly with VUE3 and summarize common API functions!

  • Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有两个被更名:
    • beforeDestroy改名为beforeUnmount
    • destroyed改名为unmounted
  • Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
    • beforeCreate===>setup()
    • created===>setup()
    • beforeMount===>onBeforeMount
    • mounted===>onMounted
    • beforeUpdate===>onBeforeUpdate
    • updated===>onUpdated
    • beforeUnmount===>onBeforeUnmount
    • unmounted===>onUnmounted

9.自定义hook函数

  • 什么是hook?——本质是一个函数,把setup函数中使用的Composition API进行了封装
  • 类似于Vue2.x中的mixin
  • 自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂

10.toRef

  • 作用:创建一个 ref 对象,其 value 值指向另一个对象中的某个属性
  • 语法:const name = toRef(person, 'name')
  • 应用:要将响应式对象中的某个属性单独提供给外部使用,并且还不会丢失响应式的时候
  • 扩展:toRefstoRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)

三、其它 Composition API

1.shallowReactive 与 shallowRef

  • shallowReactive:只处理对象最外层属性的响应式(浅响应式)
  • shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理
  • 什么时候使用?
    • 如果有一个对象数据,结构比较深,但变化时只是外层属性变化 ===> shallowReactive
    • 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换 ===> shallowRef

2.readonly 与 shallowReadonly

  • readonly:让一个响应式数据变为只读的(深只读)
  • shallowReadonly:让一个响应式数据变为只读的(浅只读)
  • 应用场景:不希望数据被修改时

3.toRaw 与 markRaw

  • toRaw:
    • 作用:将一个由reactive生成的响应式对象转为普通对象
    • 使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新
  • markRaw:
    • 作用:标记一个对象,使其永远不会再成为响应式对象
    • 应用场景:
      • 有些值不应被设置为响应式的,例如复杂的第三方类库等
      • 当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能

4.customRef

  • 作用:创建一个自定义的ref,并对其依赖项跟踪和更新触发进行显式控制
  • 实现防抖效果:


Copy after login

5.provide 与 inject

Get started quickly with VUE3 and summarize common API functions!

  • 作用:实现祖先组件与后代组件间通信
  • 套路:祖先组件有一个provide选项来提供数据,后代组件有一个inject选项来开始使用这些数据
  • 具体写法:

祖先组件中:

setup() {
    ......
    let car = reactive({
        name: '奔驰',
        price: '40万'
    })
    provide('car', car)
    ......}
Copy after login

后代组件中:

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

6.响应式数据的判断

  • isRef:检查一个值是否为一个 ref 对象
  • isReactive:检查一个对象是否是由reactive创建的响应式代理
  • isReadonly:检查一个对象是否是由readonly创建的只读代理
  • isProxy:检查一个对象是否是由reactive或者readonly方法创建的代理

四、Composition API 的优势

1.Options API 存在的问题

使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改。
Get started quickly with VUE3 and summarize common API functions!
Get started quickly with VUE3 and summarize common API functions!

2.Composition API 的优势

我们可以更加优雅地组织我们的代码、函数,让相关功能的代码更加有序地组织在一起。
Get started quickly with VUE3 and summarize common API functions!
Get started quickly with VUE3 and summarize common API functions!

五、新的组件

1.Fragment

  • 在Vue2中,组件必须有一个根标签
  • 在Vue3中,组件可以没有根标签,内部会将多个标签包含在一个Fragment虚拟元素中
  • 好处:减少标签层级,减小内存占用

2.Teleport

  • 什么是Teleport?——Teleport是一种能够将我们的组件html结构移动到指定位置的技术

    

我是一个弹窗

Copy after login

3.Suspense

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
  • 使用步骤:

异步引入组件:

import {
    defineAsyncComponent
} from 'vue'
const Child = defineAsyncComponent(() => import('./components/Child.vue'))
Copy after login

使用Suspense包裹组件,并配置好defaultfallback

Copy after login

六、其他

1.全局API的转移

  • Vue2.x有许多全局API和配置
    • 例如:注册全局组件、注册全局指令等
// 注册全局组件
Vue.component('MyButton', {
    data: () => ({
        count: 0
    }),
    template: ''
})

// 注册全局指令
Vue.directive('focus', {
    inserted: el => el.focus()
})
Copy after login
  • Vue3.0中对这些API做出了调整
    • 将全局的API,即:Vue.xxx调整到应用实例(app)上
2.x全局API(Vue3.x实例API(app
Vue.config.xxxapp.config.xxx
Vue.config.productionTip移除
Vue.componentapp.component
Vue.directiveapp.directive
Vue.mixinapp.mixin
Vue.useapp.use
Vue.prototypeapp.config.globalProperties

2.其他改变

  • data选项应始终被声明为一个函数
  • 过渡动画类名的更改:

Vue2.x写法:

.v-enter,
.v-leave-to {
    opacity: 0;}.v-leave,
.v-enter-to {
    opacity: 1;}
Copy after login

Vue3.x写法:

.v-enter-from,
.v-leave-to {
    opacity: 0;}.v-leave-from,
.v-enter-to {
    opacity: 1;}
Copy after login
  • 移除keyCode作为v-on的修饰符,同时也不再支持Vue.config.keyCodes.xxx(按键别名)
  • 移除v-on.native修饰符

父组件中绑定事件:

Copy after login

子组件中声明自定义事件:

Copy after login

  • 移除过滤器filter
    过滤器虽然看起来很方便,但它需要一个自定义语法,打破大括号内表达式“只是JavaScript”的假设,这不仅有学习成本,而且有实现成本,建议用方法调用或计算属性去替代过滤器

The above is the detailed content of Get started quickly with VUE3 and summarize common API functions!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!