Vue3.0 有哪些重要的新功能
可使用 vite 安装
(后面会讲 vite)
createApp
// vue2.x
const app = new Vue({ /* 选项 */ })
// vue3
const app = Vue.createApp({ /* 选项 */ })
全局 API
// 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
setup使用:
setup(props, { emit }) { }
生命周期
已讲过
多事件处理
<!-- 在 methods 里定义 one two 两个函数 -->
<button @click="one($event), two($event)">
Submit
</button>
Fragment
取消了 v2.x 的“一个组件必须有一个根元素”
<!-- 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
<!-- vue 2.x -->
<MyComponent v-bind:title.sync="title" />
<!-- vue 3.x -->
<MyComponent v-model:title="title" />
文档
demo 代码参考 VModel/index.vue
异步组件
新增 defineAsyncComponent
方法。
import { createApp, defineAsyncComponent } from 'vue'
createApp({
// ...
components: {
AsyncComponent: defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
}
})
vue2.x 写法如下
new Vue({
// ...
components: {
'my-component': () => import('./my-async-component.vue')
}
})
vue3 移除了过滤器 filter
<!-- 以下 filter 在 vue3 中不可用了!!! -->
<!-- 在双花括号中 -->
{{ message | capitalize }}
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
Teleport
<!-- 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
当内容组件未加载完成时,先显示 loading 的内容。
<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 的指南