vue2 vue3 packages single-file components into independent js files, dynamically loads components, and asynchronously loads components

1. I was tricked by myself (demand)

What I want is "asynchronous loading of components", but based on previous experience, the search keyword is "dynamic loading of components"

"Dynamic loading components" has another meaning in vue.

In addition, the content searched for the keyword "package single file components into independent js" is not what I want.

My requirement is to package a single file component into an independent js file, and then load it when the page needs it, instead of loading everything

(2)Solution

Directly view the official documentation "Asynchronous Components" related articles

(3)A simple example

The trick is very simple, I worked on it for several days, and even asked a master to help me deal with it (I guess there was something wrong with my description, he didn't really understand what I meant, and he didn't solve it)

cesi.vue a simple module

<template>
<div>
  测试模块
</div>
</template>

<script>
export default {
  name: "cesi",
  data(){
    return{
    }
  },
  methods: {
  }
}
</script>

<style scoped>

</style>

Other places where dynamic references are needed

<template>
  <div class='LeftAd'>
    <div @click="add">点击</div>
<!--    <img src="/static/img/LeftAd.png"/>-->
    <component v-bind:is="name"></component>
  </div>
</template>

<script>
import Vue from 'vue'
Vue.component('cesi', function (resolve) {
// 这个特殊的 `require` 语法将会告诉 webpack
// 自动将你的构建代码切割成多个包,这些包
// 会通过 Ajax 请求加载
  require(['./cesi'], resolve)
})

export default {
  name: "LeftAd",
  data(){
    return{
      name:''
    }
  },
  methods: {
    add(){
       this.name ='cesi'
    }
  }
}
</script>

<style>
</style>

Key code:

(1)<component v-bind:is="name"></component> This is to dynamically load different components based on name

(2)Vue.component('cesi', function (resolve) {require(['./cesi'], resolve)})

This line of code indicates that this component will be loaded at the appropriate time in the form of ajax.

When running npm run build cesi.vue will be packaged into a separate js file.

Only when this.name ='cesi' is triggered after clicking the div and cesi.vue is actually used, Vue will automatically request the js file from the server to load the component. There is no need to worry about how to load it.

Guess you like

Origin blog.csdn.net/tangshangkui/article/details/128926041