首页 > 其他分享 >异步组件

异步组件

时间:2022-11-02 18:46:55浏览次数:49  
标签:异步 const name .. xhr 组件

异步组件

// index.vue
import { defineAsyncComponent } from 'vue'
const Dialog = defineAsyncComponent(() => import('./Dialog/index.vue'))

// vue3 内置组件, 用于协调对组件树中嵌套的异步依赖的处理。
// 接受两个插槽:#default 和 #fallback。它将在内存中渲染默认插槽的同时展示后备插槽内容。
// 如果在渲染时遇到异步依赖项 (异步组件和具有 async setup() 的组件),它将等到所有异步依赖项解析完成时再显示默认插槽。
<Suspense>
  <template #default>
    <Dialog></Dialog>
  </template>
  <template #fallback>
    <div>loading....</div>
  </template>
</Suspense>


// Dialog/index.vue
import { axios, http } from '../../service'
const list = await http('../../../public/data.json') //
const result = await axios()
<ul>
  <li v-for="item of list" :key="item.name">{{ item.name }}</li>
</ul>

service/index.ts

  type NameList = {
  name: string
}

export const http = (url: string): Promise<NameList[]> => {
  return new Promise((resolve, reject) => {
    try {
      const xhr: XMLHttpRequest = new XMLHttpRequest()
      xhr.open('Get', url)
      xhr.onreadystatechange = () => {
        if (xhr.status === 200 && xhr.readyState === 4) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
      xhr.send(null)
    } catch (error) {
      reject('异常错误') // 处理reject时 没有trycath 会报错: Unhandled error during execution of setup function 
    }
  })
}

export const axios = (): Promise<NameList[]> => {
  return new Promise((resolve, reject) => {
    const data = [{ name: '苹果' }, { name: '香蕉' }, { name: '西瓜' }, { name: '哈密瓜' }]
    setTimeout(() => {
      resolve(data)
    }, 3000)
  })
}


标签:异步,const,name,..,xhr,组件
From: https://www.cnblogs.com/JunLan/p/16851963.html

相关文章