vue 异步组件 使用方式

异步组件的应用场景

摘自vue官网

大型应用中,我们可能需要将应用分割成小一些的代码块,并且只在需要的时候从服务器加载一个模块。
为了简化,Vue 允许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义。
Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染。

在webpack项目中使用

在这里插入图片描述

全局注册

Main.js

const AsyncComponent = Vue.component('async-component', function (resolve) {
//延时演示
  setTimeout(function () {
          require(['./components/AsyncComponent.vue'], resolve)
      },5000);
});

app.vue

<template>
  <div id="app">
    <async-component></async-component>
  </div>
</template>
<script>
export default {
  name: 'App',
}
</script>

AsyncComponent

<template>
    <div>
        <center>
            <h1>
                my name is async
            </h1>
        </center>
    </div>
</template>

局部注册

<template>
  <div id="app">
    <async-component></async-component>
  </div>
</template>
<script>
export default {
  name: 'App',
  components: {
      'async-component': function (resolve) {
          //延时演示
          setTimeout(function () {
              require(['./components/AsyncComponent.vue'], resolve)
          }, 5000);
      }
  }
}
</script>

使用vue自带的工厂函数注册

<template>
    <div id="app">
        <async-component></async-component>
    </div>
</template>
<script>
    import loading from './components/Loading.vue'
    import error from './components/Error.vue'
    const AsyncComponent = () => ({
        // 需要加载的组件 (应该是一个 `Promise` 对象)
        component: new Promise((reslove) => {
            setTimeout(()=>{
                require(["./components/AsyncComponent.vue"], reslove)
            },1000);
        }),
        // 异步组件加载时使用的组件
        loading: loading,
        // 加载失败时使用的组件
        error: error,
        // 展示加载时组件的延时时间。默认值是 200 (毫秒)
        delay: 200,
        // 如果提供了超时时间且组件加载也超时了,
        // 则使用加载失败时使用的组件。默认值是:`Infinity`
        timeout: 3000
    });
    export default {
        name: 'App',
        components: {
            'async-component': AsyncComponent
        }
    }
</script>

git 示例

https://gitee.com/study_model/vue-pack-study.git

查看不同分支

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SUNbrightness

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值