解答-3
Vue3.0 有哪些重要的新功能
(切记,不要像背诵课文似的)
我花了 3 个晚上的业余时间,详细对比了 v2 和 v3 的文档目录,找出了以下比较重要的改动。 只说重点改动,足够回复面试题了。要看详细的,需要去查阅文档。
另外,只说使用上的,不说原理上的。
可使用 vite 安装
(后面会讲 vite)
createApp
js
// vue2.x
const app = new Vue({ /* 选项 */ })
// vue3
const app = Vue.createApp({ /* 选项 */ })全局 API
js
// vue2.x
Vue.use(/* ... */)
Vue.mixin(/* ... */)
Vue.component(/* ... */)
Vue.directive(/* ... */)
// vue3
app.use(/* ... */)
app.mixin(/* ... */)
app.component(/* ... */)
app.directive(/* ... */)emits
组件中 emits: ['fnName'] ,否则有警告 Extraneous non-emits event listeners
生命周期
已讲过
多事件处理
html
<!-- 在 methods 里定义 one two 两个函数 -->
<button @click="one($event), two($event)">
Submit
</button>Fragment
取消了 v2.x 的“一个组件必须有一个根元素”
html
<!-- vue2.x 组件模板 -->
<template>
<div class="blog-post">
<h3>{{ title }}</h3>
<div v-html="content"></div>
</div>
</template>
<!-- vue3 组件模板 -->
<template>
<h3>{{ title }}</h3>
<div v-html="content"></div>
</template>去掉了 .sync
html
<!-- vue 2.x -->
<MyComponent v-bind:title.sync="title" />
<!-- vue 3.x -->
<MyComponent v-model:title="title" />文档
- vue2.x https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-修饰符
- vue3 https://v3.cn.vuejs.org/guide/component-custom-events.html#v-model-参数
demo 代码参考 VModel/index.vue
异步组件
新增 defineAsyncComponent 方法。
js
import { createApp, defineAsyncComponent } from 'vue'
createApp({
// ...
components: {
AsyncComponent: defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
}
})vue2.x 写法如下
js
new Vue({
// ...
components: {
'my-component': () => import('./my-async-component.vue')
}
})vue3 移除了过滤器 filter
html
<!-- 以下 filter 在 vue3 中不可用了!!! -->
<!-- 在双花括号中 -->
{{ message | capitalize }}
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>Teleport
html
<!-- data 中设置 modalOpen: false -->
<button @click="modalOpen = true">
Open full screen modal! (With teleport!)
</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
telePort 弹窗 (父元素是 body)
<button @click="modalOpen = false">Close</button>
</div>
</div>
</teleport>Suspense
【注意】Suspense 是一个实验性的 API ,后面可能会改变 —— v3.0.2
当内容组件未加载完成时,先显示 loading 的内容。
html
<Suspense>
<template>
<Test1/> <!-- 是一个异步组件 -->
</template>
<!-- #fallback 就是一个具名插槽。即:
Suspense 组件内部,有两个 slot ,
其中一个具名为 fallback -->
<template #fallback>
Loading...
</template>
</Suspense>demo 代码参考 SuspenseTest/index.vue
Composition API
主要的功能有:
- reactive
- ref 相关
- readonly
- computed
- watch
- watchEffect
- setup
- 各生命周期钩子函数
上述仅仅是比较重要改动,足够应对面试题了。 全面的改动,可以查看 v2 升级 v3 的指南 https://v3.cn.vuejs.org/guide/migration/introduction.html

讨论区
欢迎留下想法与补充