1、Vue3 新特性

1-1 组合式API setup

1-2 Fragment翻译为:“碎片”

Teleport 提供了一种干净的方法,允许我们控制在 DOM 中哪个父节点下渲染了 HTML,而不必求助于全局状态或将其拆分为两个组件。
让我们修改 modal-button 以使用 ,并告诉 Vue “将这个 HTML 传送到‘body’标签下”。

  1. app.component('modal-button', {
  2. template: `
  3. <button @click="modalOpen = true">
  4. Open full screen modal! (With teleport!)
  5. </button>
  6. <teleport to="body">
  7. <div v-if="modalOpen" class="modal">
  8. <div>
  9. I'm a teleported modal!
  10. (My parent is "body")
  11. <button @click="modalOpen = false">
  12. Close
  13. </button>
  14. </div>
  15. </div>
  16. </teleport>
  17. `,
  18. data() {
  19. return {
  20. modalOpen: false
  21. }
  22. }
  23. })

2、非兼容的变更

2-1 全局API

调用 createApp 返回一个应用实例,一个 Vue 3 中的新概念。

  1. import { createApp } from 'vue'
  2. const app = createApp({})

Vue.prototype 替换为 config.globalProperties

在 Vue 2 中, Vue.prototype 通常用于添加所有组件都能访问的 property。
在 Vue 3 中与之对应的是 config.globalProperties。这些 property 将被复制到应用中,作为实例化组件的一部分。

  1. // 之前 - Vue 2
  2. Vue.prototype.$http = () => {}
  1. // 之后 - Vue 3
  2. const app = createApp({})
  3. app.config.globalProperties.$http = () => {}

Vue.extend 移除

在 Vue 2.x 中,Vue.extend 曾经被用于创建一个基于 Vue 构造函数的“子类”,其参数应为一个包含组件选项的对象。在 Vue 3.x 中,我们已经没有组件构造器的概念了。应该始终使用 createApp 这个全局 API 来挂载组件:

  1. // 之前 - Vue 2
  2. // 创建构造器
  3. const Profile = Vue.extend({
  4. template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  5. data() {
  6. return {
  7. firstName: 'Walter',
  8. lastName: 'White',
  9. alias: 'Heisenberg'
  10. }
  11. }
  12. })
  13. // 创建一个 Profile 的实例,并将它挂载到一个元素上
  14. new Profile().$mount('#mount-point')
  1. // 之后 - Vue 3
  2. const Profile = {
  3. template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  4. data() {
  5. return {
  6. firstName: 'Walter',
  7. lastName: 'White',
  8. alias: 'Heisenberg'
  9. }
  10. }
  11. }
  12. Vue.createApp(Profile).mount('#mount-point')

组件集成

在 Vue 3 中,我们强烈建议使用 组合式 API 来替代继承与 mixin。如果因为某种原因仍然需要使用组件继承,你可以使用 extends选项 来代替 Vue.extend。

插件开发者须知

在 UMD 构建中,插件开发者使用 Vue.use 来自动安装插件是一个通用的做法。例如,官方的 vue-router 插件是这样在浏览器环境中自行安装的:

  1. var inBrowser = typeof window !== 'undefined'
  2. /* … */
  3. if (inBrowser && window.Vue) {
  4. window.Vue.use(VueRouter)
  5. }

由于 use 全局 API 在 Vue 3 中已无法使用,因此此方法将无法正常工作,并且调用 Vue.use() 现在将触发一个警告。取而代之的是,开发者必须在应用实例上显式指定使用此插件:

  1. const app = createApp(MyApp)
  2. app.use(VueRouter)

2-2 模板指令

组件上v-model用法已更改,以替换v-bind.sync
  1. <ChildComponent v-model:title="pageTitle" v-model:content="pageContent" />
  2. <!-- 是以下的简写: -->
  3. <ChildComponent
  4. :title="pageTitle"
  5. @update:title="pageTitle = $event"
  6. :content="pageContent"
  7. @update:content="pageContent = $event"
  8. />