Vue3-7-新组件

新组件

Fragment(片断)

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

Teleport(瞬移)

  1. Teleport 提供了一种干净的方法, 让组件的html在父组件界面外的特定标签(很可能是body)下插入显示
  2. 通过Teleport与to可以把元素放在HTML标签任意位置
  3. 点击弹出对话框
  • App.vue
<template>
  <h1>App父级组件</h1>
  <hr>
  <son></son>

</template>

<script lang="ts">

import son from './components/son.vue'
import {
      
      defineComponent} from "vue";
export default defineComponent({
      
      
  name:'App',
  components:{
      
      
    son,
  },
  setup() {
      
      


  }

})
</script>
  • son.vue
<template>
  <button @click="open=true">点击显示某个对话框</button>
  <teleport to="body">
    <div v-if="open" class="modal">
      <div>对话框</div>
      <button @click="open=false">关闭对话框</button>
    </div>
  </teleport>

  </template>
<script>
  import {
      
      ref} from 'vue'
export default {
      
      
  name: "son",
  setup(){
      
      
    // 对话框显示或隐藏
    const open =ref(false)
    return{
      
      
      open
    }
  }
}
</script>

<style scoped>
.modal {
      
      
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: rgba(0,0,0,.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.modal div {
      
      
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: white;
  width: 300px;
  height: 300px;
  padding: 5px;
}
</style>

Suspense(不确定的)

  1. 它们允许我们的应用程序在等待异步组件时渲染一些后备内容,可以让我们创建一个平滑的用户体验
  2. 也就是在加载异步组件时,用一些内容展示先显示着
  3. 示例:异步加载提示
  • App.vue
<template>
  <h1>App父级组件</h1>
  <hr>
  <Suspense>
    <template #default>
<!--      异步加载-->
      <Asyncson></Asyncson>
    </template>
    <template v-slot:fallback>
<!--      加载时占位-->
      <h2>加载中</h2>
    </template>
  </Suspense>
</template>
<script lang="ts">

// import Asyncson from './components/son.vue'
// vue2中动态引入const Asyncson=()=>import('./components/son.vue')
const Asyncson =defineAsyncComponent(()=>import('./components/son.vue'))
import {
      
      defineAsyncComponent, defineComponent} from "vue";
export default defineComponent({
      
      
  name:'App',
  components:{
      
      
    Asyncson,
  },
  setup() {
      
      


  }

})
</script>
  • son.vue
<template>
  <h2>son组件</h2>
  <h3>{
   
   {msg}}</h3>
</template>
<script>

export default {
      
      
  name: "son",
  setup(){
      
      
    return new Promise((resolve,rejecr)=>{
      
      
      setTimeout(()=>{
      
      
        resolve({
      
      msg:'hello vue3'})
      },1000)
    })
  }
}
</script>

<style scoped>
</style>

猜你喜欢

转载自blog.csdn.net/weixin_64925940/article/details/124899870