vue3新增Suspense元件

2021-10-09 16:19:33 字數 1819 閱讀 7583

在開始介紹vue的suspense元件之前,我們有必要先了解一下react的suspense元件,因為他們的功能類似。

react 16.6 新增了元件,讓你可以「等待」目標**載入,並且可以直接指定乙個載入的介面(像是個 spinner),讓它在使用者等待的時候顯示:

const profilepage = react.

lazy((

)=>

import

('./profilepage'))

;// 懶載入

// 在 profilepage 元件處於載入階段時顯示乙個 spinner

>

>

<

/suspense>

suspense 元件常常和 react.lazy 配合使用。

react.lazy 函式能讓你像渲染常規元件一樣處理動態引入(的元件)。

react.lazy 接受乙個函式,這個函式需要動態呼叫 import()。它必須返回乙個 promise,該 promise 需要 resolve 乙個 default export 的 react 元件。

然後應在 suspense 元件中渲染 lazy 元件,如此使得我們可以使用在等待載入 lazy 元件時做優雅降級(如 loading 指示器等)。

import react,

from

'react'

;const othercomponent = react.

lazy((

)=>

import

('./othercomponent'))

;function

mycomponent()

>

>

<

/suspense>

<

/div>);

}

注意:元件可以接受任意 props,包括基本資料型別,react 元素以及函式。

defineasynccomponent 類似於 react.lazy 函式。

import

from

'vue'

const asynccomp =

defineasynccomponent((

)=>

import

('./components/asynccomponent.vue'))

component

('async-component'

, asynccomp)

vue 中也有 suspense 元件,和 react 中的類似。

const othercomponent =

defineasynccomponent((

)=>

import

('./othercomponent'))

;>

>

<

/template>

loading ...

<

/template>

<

/suspense>

<

/template>

具名插槽的縮寫是在 vue2.6.0 新增,跟 v-on 和 v-bind 一樣,v-slot 也有縮寫,即把引數之前的所有內容 (v-slot:) 替換為字元 #。例如 v-slot:header 可以被重寫為 #header:

Vue 3 元件註冊

上一節實驗中,我們大概了解了一下元件的基礎,這一節實驗我們要深入元件註冊。我們在註冊元件的時候,我們都會給元件起乙個名字,就好像我們人的名字一樣。需要注意的是,我們的元件名字是有一些規範的,一般這種單檔案元件,我們強烈推薦使用字母全小寫且必須包含乙個連字元,全部小寫字母,單詞使用中華線 隔開。例如我...

vue3 元件通訊 vue router

關於元件通訊 1.父子元件間傳值 props emit parent children ref 2.非父子元件傳值 事件匯流排 原理就是建立乙個公共的js檔案,專門用來傳遞資訊 import vue from vue export default new vue 在需要傳遞訊息的地方引入 impor...

Vue3元件傳參

總結沒啥好說的,淦就完事了,按照自己的認知簡單的整理了一下vue3的元件傳參 如下 示例 子元件 click childemit 傳值給父元件button div template export default return script 父元件 my emit parentemit child d...