FE-DSHUI / DSHUI

前端王者小分队读书会
4 stars 1 forks source link

《vue3的新增组件-异步组件Suspense&模板组件Teleport》 #86

Open isbaselvy opened 3 years ago

isbaselvy commented 3 years ago

异步组件

异步组件使用场景

Suspense,异步组件,在template中使用,官网中未有详细提及,可能会有变化

  <Suspense>
    <template #default>
      <!-- 异步组件,当setup方法中的异步方法执行完后展示 -->
    </template>
    <template #fallback>
      <!-- 默认加载的内容,比如loading或者图标 -->
    </template>
  </Suspense>

Suspense的用法:场景-加载数据,加载过程中显示loading,加载完毕展示内容

父组件App.vue

<template>
<div>
  <div v-if="error">
    {{error}}
  </div>
   <Suspense v-else>
    <template #default>
      <User />
    </template>
    <template #fallback>
      loading
    </template>
  </Suspense>
</div>

</template>

<script lang="ts">
import { defineComponent, onErrorCaptured, ref } from 'vue'
import User from '@/components/User.vue'

export default defineComponent({
  name: 'APP',
  components: {
    User
  },
  setup () {
    const error = ref('')
    onErrorCaptured(err => {
      error.value = err as string
      return true
    })
    console.log(11111111111, error)
    return {
      error
    }
  }
})
</script>

子组件User.vue

<template>
  <div>{{ msgRef }}</div>
</template>

<script>
import { defineComponent, ref } from 'vue'

export default defineComponent({
  name: 'User',
  async setup () {
    const promise = new Promise((resolve) => {
      setTimeout(() => {
        resolve('success!!!!')
      }, 2000)
    })

    const msg = await promise

    const msgRef = ref('')
    msgRef.value = msg
    return {
      msgRef
    }
  }
})
</script>

将suspense封装成组件

suspeseWithError组件

<template>
<div>
  <slot v-if="error" name="error" :err="error">
    {{error}}
  </slot>
  <Suspense v-else>
    <template #default>
      <!-- 异步组件,当setup方法中的异步方法执行完后展示 -->
      <slot name="default"></slot>
    </template>
    <template #fallback>
      <!-- 默认加载的内容,比如loading或者图标 -->
      <slot name="fallback"></slot>
    </template>
  </Suspense>
</div>

</template>

<script lang="ts">
import { defineComponent, onErrorCaptured, ref } from 'vue'

export default defineComponent({
  name: 'SuspenseWithError',
  setup () {
    const error = ref('')
    onErrorCaptured(err => {
      error.value = err as string
      return true
    })
    return {
      error
    }
  }
})
</script>

使用

  <SuspenseWithError>
    <template #error="{ err }">
      {{err}}
    </template>
    <template #default>
      <User />
    </template>
    <template #fallback>
      loading
    </template>
  </SuspenseWithError>

Teleport

teleport