Vue高级特性之异步组件

当我们的项目达到一定的规模时,对于某些组件来说,我们并不希望一开始全部加载,而是需要的时候进行加载。这样做可以很好的提高用户体验,加快页面的载入速度,为此Vue 提供了异步组件的性能优化方案。

1. Vue2 的异步组件

# 全局注册, 可以写在 main.js 里
Vue.component(
  'MyComp',
  () => import('./my-comp')
)
# 局部注册
<script>
export default {
  components: {
    MyComp: () => import('./my-comp')
  }
}
</script>

写个demo小试牛刀:

<!-- 父组件 -->
<template>
    <div>
        <Button @click="show = true">显示Form</Button>
        <FormCom v-if="show" />
    </div>
</template>
 
<script>
export default {
    components: {
        FormCom: () => import('./FormCom')
    },
    data() {
        return {
            show: false
        }
    }
}
</script>
 
<!-- 子组件 -->
<template>
  <input type="text" :value="value">
</template>
 
<script>
export default {
  data() {
    return {
      value: ''
    }
  }
}
</script>

2. Vue3 的异步组件

Vue3中为我们提供了一个方法,即 defineAsyncComponent,这个方法可以传递函数类型的参数:

# 局部注册
<template>
  <article-list />
</template>

<script setup lang="ts">
import { defineAsyncComponent } from 'vue'

const ArticleList = defineAsyncComponent(
  () => import('@/components/ArticleList.vue')
)
</script>
# 全局注册
import { createApp, defineAsyncComponent } from 'vue'
import App from '@/App.vue'

const app = createApp(App)

app.component('ArticleList', defineAsyncComponent(() =>
  import('@/components/ArticleList.vue')
))

app.mount('#app')

End-------------------------

猜你喜欢

转载自blog.csdn.net/u011690675/article/details/130258064
今日推荐