VUE3新组件 — Vue3

编程入门 行业动态 更新时间:2024-10-14 20:21:46

VUE3新<a href=https://www.elefans.com/category/jswz/34/1771375.html style=组件 — Vue3"/>

VUE3新组件 — Vue3

1. 新组件

1) Fragment(片断)

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

2) Teleport(瞬移)

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

ModalButton.vue

<template><button @click="modalOpen = true">Open full screen modal! (With teleport!)</button><teleport to="body"><div v-if="modalOpen" class="modal"><div>I'm a teleported modal! (My parent is "body")<button @click="modalOpen = false">Close</button></div></div></teleport>
</template><script>
import { ref } from 'vue'
export default {name: 'modal-button',setup () {const modalOpen = ref(false)return {modalOpen}}
}
</script><style>
.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>

App.vue

<template><h2>App</h2><modal-button></modal-button>
</template><script lang="ts">
import ModalButton from './ModalButton.vue'export default {setup() {return {}},components: {ModalButton}
}
</script>

3) Suspense(不确定的)

  • 它们允许我们的应用程序在等待异步组件时渲染一些后备内容,可以让我们创建一个平滑的用户体验
<template><Suspense><template v-slot:default><AsyncComp/><!-- <AsyncAddress/> --></template><template v-slot:fallback><h1>LOADING...</h1></template></Suspense>
</template><script lang="ts">
/* 
异步组件 + Suspense组件
*/
// import AsyncComp from './AsyncComp.vue'
import AsyncAddress from './AsyncAddress.vue'
import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() => import('./AsyncComp.vue'))
export default {setup() {return {}},components: {AsyncComp,AsyncAddress}
}
</script>
  • AsyncComp.vue
<template><h2>AsyncComp22</h2><p>{{msg}}</p>
</template><script lang="ts">export default {name: 'AsyncComp',setup () {// return new Promise((resolve, reject) => {//   setTimeout(() => {//     resolve({//       msg: 'abc'//     })//   }, 2000)// })return {msg: 'abc'}}
}
</script>
  • AsyncAddress.vue
<template>
<h2>{{data}}</h2>
</template><script lang="ts">
import axios from 'axios'
export default {async setup() {const result = await axios.get('/data/address.json')return {data: result.data}}
}
</script>

更多推荐

VUE3新组件 — Vue3

本文发布于:2023-12-03 19:36:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1657021.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!