search
HomeWeb Front-endVue.jsGet started quickly with VUE3 and summarize common API functions!

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

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 <project-name>

## 进入工程目录
cd <project-name>

## 安装依赖
npm install

## 运行
npm run dev

2. Commonly used Composition API

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

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() {}})
  • 存在问题:
    • 新增属性、删除属性,界面不会更新
    • 直接通过下标修改数组,界面不会自动更新

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'

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]
        }
    })}

watch函数

  • 与Vue2.x中watch配置功能一致
  • 两个小“坑”:
    • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)
    • 监视reactive定义的响应式数据中某个属性时:deep配置有效
// 情况一:监视ref定义的响应式数据
watch(sum, (newValue, oldValue) => {
    console.log(&#39;sum变化了&#39;, newValue, oldValue)
}, {
    immediate: true
})

// 情况二:监视多个ref定义的响应式数据
watch([sum, msg], (newValue, oldValue) => {
    console.log(&#39;sum或msg变化了&#39;, newValue, oldValue)
})

/*
情况三:监视reactive定义的响应式数据
若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue
若watch监视的是reactive定义的响应式数据,则强制开启了深度监视
*/
watch(person, (newValue, oldValue) => {
    console.log(&#39;person变化了&#39;, newValue, oldValue)
}, {
    immediate: true,
    deep: false
}) // 此处的deep配置不再奏效

// 情况四:监视reactive定义的响应式数据中的某个属性
watch(() => person.job, (newValue, oldValue) => {
    console.log(&#39;person的job变化了&#39;, newValue, oldValue)
}, {
    immediate: true,
    deep: true
})

// 情况五:监视reactive定义的响应式数据中的某些属性
watch([() => person.job, () => person.name], (newValue, oldValue) => {
    console.log(&#39;person的job变化了&#39;, newValue, oldValue)
}, {
    immediate: true,
    deep: true
})

// 特殊情况
watch(() => person.job, (newValue, oldValue) => {
    console.log(&#39;person的job变化了&#39;, newValue, oldValue)
}, {
    deep: true
}) // 此处由于监视的是reactive所定义的对象中的某个属性,所以deep配置有效

watchEffect函数

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

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,并对其依赖项跟踪和更新触发进行显式控制
  • 实现防抖效果:
<template>
    <input type="text" v-model="keyword">
    <h3 id="keyword">{{keyword}}</h3>
</template>

<script>
import {
    ref,
    customRef
} from &#39;vue&#39;
export default {
    name: &#39;Demo&#39;,
    setup() {
        // let keyword = ref(&#39;hello&#39;) //使用Vue准备好的内置ref
        // 自定义一个myRef
        function myRef(value, delay) {
            let timer
            // 通过customRef去实现自定义
            return customRef((track, trigger) => {
                return {
                    get() {
                        track() // 告诉Vue这个value值是需要被“追踪”的
                        return value
                    },
                    set(newValue) {
                        clearTimeout(timer)
                        timer = setTimeout(() => {
                            value = newValue
                            trigger() // 告诉Vue去更新界面
                        }, delay)
                    }
                }
            })
        }
        let keyword = myRef(&#39;hello&#39;, 500) // 使用程序员自定义的ref
        return {
            keyword
        }
    }
}
</script>

5.provide 与 inject

Get started quickly with VUE3 and summarize common API functions!

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

祖先组件中:

setup() {
    ......
    let car = reactive({
        name: &#39;奔驰&#39;,
        price: &#39;40万&#39;
    })
    provide(&#39;car&#39;, car)
    ......}

后代组件中:

setup(props, context) {
    ......
    const car = inject(&#39;car&#39;)
    return {
        car    }
    ......}

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结构移动到指定位置的技术
<teleport to="移动位置">
    <div v-if="isShow" class="mask">
        <div class="dialog">
            <h3 id="我是一个弹窗">我是一个弹窗</h3>
            <button @click="isShow = false">关闭弹窗</button>
        </div>
    </div>
</teleport>

3.Suspense

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

异步引入组件:

import {
    defineAsyncComponent
} from &#39;vue&#39;
const Child = defineAsyncComponent(() => import(&#39;./components/Child.vue&#39;))

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

<template>
    <div class="app">
        <h3 id="我是App组件">我是App组件</h3>
        <Suspense>
            <template v-slot:default>
                <Child />
            </template>
            <template v-slot:fallback>
                <h3 id="加载中">加载中...</h3>
            </template>
        </Suspense>
    </div>
</template>

六、其他

1.全局API的转移

  • Vue2.x有许多全局API和配置
    • 例如:注册全局组件、注册全局指令等
// 注册全局组件
Vue.component(&#39;MyButton&#39;, {
    data: () => ({
        count: 0
    }),
    template: &#39;<button @click="count++">Clicked {{ count }} times.</button>&#39;
})

// 注册全局指令
Vue.directive(&#39;focus&#39;, {
    inserted: el => el.focus()
})
  • Vue3.0中对这些API做出了调整
    • 将全局的API,即:Vue.xxx调整到应用实例(app)上
2.x全局API(Vue 3.x实例API(app
Vue.config.xxx app.config.xxx
Vue.config.productionTip 移除
Vue.component app.component
Vue.directive app.directive
Vue.mixin app.mixin
Vue.use app.use
Vue.prototype app.config.globalProperties

2.其他改变

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

Vue2.x写法:

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

Vue3.x写法:

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

父组件中绑定事件:

<my-component
v-on:close="handleComponentEvent"
v-on:click="handleNativeClickEvent" />

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

<script>
    export default {
        emits: [&#39;close&#39;] // 这里声明的事件才算作自定义事件,所以在父组件中click是原生事件
    }
</script>
  • 移除过滤器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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. Backend Frameworks: Clarifying the DistinctionVue.js vs. Backend Frameworks: Clarifying the DistinctionApr 25, 2025 am 12:05 AM

Vue.js is a front-end framework, and the back-end framework is used to handle server-side logic. 1) Vue.js focuses on building user interfaces and simplifies development through componentized and responsive data binding. 2) Back-end frameworks such as Express and Django handle HTTP requests, database operations and business logic, and run on the server.

Vue.js and the Frontend Stack: Understanding the ConnectionsVue.js and the Frontend Stack: Understanding the ConnectionsApr 24, 2025 am 12:19 AM

Vue.js is closely integrated with the front-end technology stack to improve development efficiency and user experience. 1) Construction tools: Integrate with Webpack and Rollup to achieve modular development. 2) State management: Integrate with Vuex to manage complex application status. 3) Routing: Integrate with VueRouter to realize single-page application routing. 4) CSS preprocessor: supports Sass and Less to improve style development efficiency.

Netflix: Exploring the Use of React (or Other Frameworks)Netflix: Exploring the Use of React (or Other Frameworks)Apr 23, 2025 am 12:02 AM

Netflix chose React to build its user interface because React's component design and virtual DOM mechanism can efficiently handle complex interfaces and frequent updates. 1) Component-based design allows Netflix to break down the interface into manageable widgets, improving development efficiency and code maintainability. 2) The virtual DOM mechanism ensures the smoothness and high performance of the Netflix user interface by minimizing DOM operations.

Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor