v-model新语法糖
默认使用modelValue
传递值。
<ChildComponent v-model="pageTitle" />
<!-- would be shorthand for: -->
<ChildComponent
:modelValue="pageTitle"
@update:modelValue="pageTitle = $event"
/>
也支持绑定不同的属性,有点像是v-model
和sync
的结合体。
<ChildComponent v-model:title="pageTitle" v-model:content="pageContent" />
<!-- would be shorthand for: -->
<ChildComponent
:title="pageTitle"
@update:title="pageTitle = $event"
:content="pageContent"
@update:content="pageContent = $event"
/>
全局API
-
不再使用
new Vue
问题 使用`new Vue`会共享一个全局配置。这对于测试来说不太友好,每个测试用例都需要一个沙盒环境,全局变量去残留一些副作用。 解决 开始使用`application`概念,创建一个`App`。
2.不再用Vue.prototype
// Vue 2
Vue.prototype.$http = () => {}
// Vue 3
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}
-
全局方法现在在
app
实例上vue2.x vue3.x ue.component app.component ue.directive app.directive Vue.mixin app.mixin Vue.use app.use
4.现在需要手动挂载根元素
app.mount("#app")
5.不能再使用Vue.nextTick/this.$nextTick
import { nextTick } from 'vue'
nextTick(() => {
// something DOM-related
})
6.$attrs
将包含class
和style
vue2.x
中,class
和style
会被直接设置在组件的根元素上并且不会出现在$attrs
中。但是在vue3
中,如果子组件只有一个根元素,则class
和style
会被直接设置在该元素上。超过一个则不会设置。如果组件中设置了inheritAttrs: false
,则无论如何都不会自动设置根元素的class
和style
。
7.$listeners
被移除
事件监听器也被包含还在了$attrs
中。
8.$children
被移除
如果想访问子组件,使用$refs
。
9.事件API被移除
$on,$off,$once
不再使用。2.x的EventBus
方法不能再使用。
10.Filter被移除
不能再用|
使用filter。
11.新特性fragments
允许组件有多个根元素!
在 2.x 中,由于不支持多根节点组件,当其被开发者意外地创建时会发出警告。结果是,为了修复这个问题,许多组件被包裹在了一个 <div>
中。
<!-- Layout.vue -->
<template>
<div>
<header>...</header>
<main>...</main>
<footer>...</footer>
</div>
</template>
在 3.x 中,组件可以包含多个根节点!但是,这要求开发者显式定义 attribute 应该分布在哪里。
<!-- Layout.vue -->
<template>
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
</template>
12.指令
指令和组件生命周期更契合,并使用统一的命名。
vue2.x | vue3.x |
---|---|
- | created (新):在元素的 attribute 或事件监听器被应用之前调用 |
bind:指令绑定到元素后调用。只调用一次 | beforeMount |
inserted:元素插入父 DOM 后调用 | mounted |
- | beforeUpdate (新):在元素本身被更新之前调用,与组件的生命周期钩子十分相似 |
update (移除) | - |
componentUpdated:一旦组件和子级被更新,就会调用这个钩子 | updated |
- | beforeUnmount (新):与组件的生命周期钩子类似,它将在元素被卸载之前调用 |
unbind | unmounted |