Vue advanced features asynchronous components

When our project reaches a certain scale, for some components, we do not want to load them all at the beginning, but load them when needed. This can greatly improve the user experience and speed up page loading. For this reason, Vue provides a performance optimization solution for asynchronous components.

1. Asynchronous components of Vue2

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

Write a demo to try out your skills:

<!-- 父组件 -->
<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. Asynchronous components of Vue3

Vue3 provides us with a method, defineAsyncComponent, which can pass function type parameters:

# 局部注册
<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-------------------------

Guess you like

Origin blog.csdn.net/u011690675/article/details/130258064