vue3 基础知识整理

API 风格

Vue 的组件可以按两种不同的风格书写:选项式 API 和组合式 API。

选项式 (Options api)

个人理解与 vue2 差不多
官方解释: 使用选项式 API,我们可以用包含多个选项的对象来描述组件的逻辑,例如 data、methods 和 mounted。选项所定义的属性都会暴露在函数内部的 this 上,它会指向当前的组件实例。

组合式 (Composition API)

vue3 新写法,推荐!
在单文件组件中,组合式 API 通常会与 <script setup>搭配使用

生命周期

vue2 options api vue3 options api vue3 composition api
beforeCreate beforeCreate setup
created created setup
beforeMount beforeMount onBeforeMount
mounted mounted onMounted
beforeUpdate beforeUpdate onBeforeUpdate
update update onUpdated
beforeDestroy beforeUnmounted onBeforeUnmount
destroyed unMounted onUnmounted
ErrorCaptured onErrorCaptured
RenderTracked onRenderTracked(dev only)
RenderTriggered onRenderTriggered(dev only)

修改
destroyed 生命周期选项被重命名为 unmounted
beforeDestroy 生命周期选项被重命名为 beforeUnmount

新增
errorCaptured:在捕获一个来自后代组件的错误时被调用。
renderTracked:跟踪虚拟 DOM 重新渲染时调用。
renderTriggered:当虚拟 DOM 重新渲染被触发时调用。

– update by 2023-5-18

创建实例

createApp

1
2
const app = createApp(App)
app.mount('#app')

注册

全局注册

我们可以使用 Vue 应用实例app.component() 方法,让组件在当前 Vue 应用中全局可用
app.component() 方法可以被链式调用

1
2
3
4
5
6
7
8
9
10
11
12
// 直接注册。
app.component(
// 注册的名字
'MyComponent',
// 组件的实现
{
/* ... */
}
)
// 引入文件
import MyComponent from './App.vue'
app.component('MyComponent', MyComponent)

局部注册

在使用