1. 新组件

Fragment(片断)

  • 在Vue2中: 组件必须有一个根标签
  • 在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中
  • 好处: 减少标签层级, 减小内存占用
  1. <template>
  2. <h2>aaaa</h2>
  3. <h2>aaaa</h2>
  4. </template>

Teleport(瞬移)

  • Teleport 提供了一种干净的方法, 让组件的html在父组件界面外的特定标签(很可能是body)下插入显示

ModalButton.vue

  1. <template>
  2. <button @click="modalOpen = true">
  3. Open full screen modal! (With teleport!)
  4. </button>
  5. <teleport to="body">
  6. <div v-if="modalOpen" class="modal">
  7. <div>
  8. I'm a teleported modal!
  9. (My parent is "body")
  10. <button @click="modalOpen = false">
  11. Close
  12. </button>
  13. </div>
  14. </div>
  15. </teleport>
  16. </template>
  17. <script>
  18. import { ref } from 'vue'
  19. export default {
  20. name: 'modal-button',
  21. setup () {
  22. const modalOpen = ref(false)
  23. return {
  24. modalOpen
  25. }
  26. }
  27. }
  28. </script>
  29. <style>
  30. .modal {
  31. position: absolute;
  32. top: 0; right: 0; bottom: 0; left: 0;
  33. background-color: rgba(0,0,0,.5);
  34. display: flex;
  35. flex-direction: column;
  36. align-items: center;
  37. justify-content: center;
  38. }
  39. .modal div {
  40. display: flex;
  41. flex-direction: column;
  42. align-items: center;
  43. justify-content: center;
  44. background-color: white;
  45. width: 300px;
  46. height: 300px;
  47. padding: 5px;
  48. }
  49. </style>

App.vue

  1. <template>
  2. <h2>App</h2>
  3. <modal-button></modal-button>
  4. </template>
  5. <script lang="ts">
  6. import ModalButton from './ModalButton.vue'
  7. export default {
  8. setup() {
  9. return {
  10. }
  11. },
  12. components: {
  13. ModalButton
  14. }
  15. }
  16. </script>

Suspense(不确定的)

  • 它们允许我们的应用程序在等待异步组件时渲染一些后备内容,可以让我们创建一个平滑的用户体验
  1. <template>
  2. <h2>父级组件</h2>
  3. <Suspense>
  4. <template #default>
  5. <AsyncComp />
  6. </template>
  7. <template #fallback>
  8. <h1>LOADING...</h1>
  9. </template>
  10. </Suspense>
  11. </template>
  12. <script lang="ts">
  13. import { defineAsyncComponent } from "vue";
  14. const AsyncComp = defineAsyncComponent(() => import("./AsyncComp.vue"));
  15. export default {
  16. components: { AsyncComp },
  17. };
  18. </script>
  • AsyncComp.vue
  1. <template>
  2. <div>子级组件</div>
  3. </template>
  4. <script lang="ts">
  5. import { defineComponent } from "vue";
  6. export default defineComponent({
  7. name: "AsyncComp",
  8. });
  9. </script>