2024-03-04
Vue
0
请注意,本文编写于 76 天前,最后修改于 76 天前,其中某些信息可能已经过时。

目录

Teleport
Suspense
全局 API 转移到应用对象
Vue3 的非兼容性改变
全局API
模板指令
组件
渲染函数
自定义元素
其他小改变
被移除的 API

Vue3 - 渐进式
JavaScript 框架

易学易用,性能出色,适用场景丰富的 Web 前端框架。

Teleport

有时我们可能会遇到这样的场景:一个组件模板的一部分在逻辑上从属于该组件,但从整个应用视图的角度来看,它在 DOM 中应该被渲染在整个 Vue 应用外部的其他地方。

这类场景最常见的例子就是全屏的模态框。理想情况下,我们希望触发模态框的按钮和模态框本身是在同一个组件中,因为它们都与组件的开关状态有关。但这意味着该模态框将与按钮一起渲染在应用 DOM 结构里很深的地方。这会导致该模态框的 CSS 布局代码很难写。

Teleport 是一种能够将我们的组件html结构移动到指定位置的技术

例如,当父组件中使用了 filter 等 css 属性时,子组件的 position 属性会失效,这时可以使用 <teleport to="dom"></teleport> 挂载到某一html结点上,to 的值为元素选择器

vue
<template> <button @click="show = true">Show Modal</button> <Teleport to="body"> <div class="modal" v-show="show"> <h2>Modal Title</h2> <p>Modal content</p> <button @click="show = false">close</button> </div> </Teleport> </template>

指定目标容器:

vue
<Teleport to="#some-id" /> <Teleport to=".some-class" /> <Teleport to="[data-teleport]" />

有条件地禁用:

vue
<Teleport to="#popup" :disabled="displayVideoInline"> <video src="./my-movie.mp4"> </Teleport>

提示

<Teleport> 挂载时,传送的 to 目标必须已经存在于 DOM 中。理想情况下,这应该是整个 Vue 应用 DOM 树外部的一个元素。如果目标元素也是由 Vue 渲染的,你需要确保在挂载 <Teleport> 之前先挂载该元素。

Suspense

实验性功能

<Suspense> 是一项实验性功能。它不一定会最终成为稳定功能,并且在稳定之前相关 API 也可能会发生变化。

等待异步组件时渲染一些额外内容,让应用有更好的用户体验

使用 Suspense 包裹组件,并配置好 defaultfallback (底层使用插槽实现)

vue
<template> <div class="outer"> <h2>App</h2> <Suspense> <template v-slot:default> <Child /> </template> <template v-slot:fallback> <h2>loading</h2> </template> </Suspense> </div> </template>

全局 API 转移到应用对象

  • app.component

    typescript
    import Hello from './Hello'; app.component('Hello', Hello);
  • app.config

    typescript
    app.config.globalProperties.x = 99; declare module 'vue' { interface ComponentCustomProperties { x: number } }
  • app.directive

    typescript
    /* main.ts */ app.directive('beauty', (element, {value}) => { element.innerText += value; element.style.color = 'red'; element.style.backgroundColor = 'skyblue'; }) /* Comp.vue */ <h3 v-beauty="count">哈哈哈</h3>
  • app.mount

  • app.unmount

    typescript
    setTimeout(() => { app.unmount(); }, 2000);
  • app.use

Vue3 的非兼容性改变

非兼容性改变 | Vue 3 迁移指南 (vuejs.org)

全局API

模板指令

组件

渲染函数

自定义元素

其他小改变

被移除的 API

本文作者:Morales

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 License 许可协议。转载请注明出处!