Vue's dynamic components and asynchronous components and keep-alive

Dynamic components and asynchronous components of vue

1. Dynamic components

Dynamic components are used , implemented component 组件through a special attributeis

Let's use an example to explain how dynamic components are used
insert image description here
. As shown in the figure above, for example, we now want to implement a function: click a tab-bar to switch the display of different components

In this case, we can achieve this through three different implementation ideas

  • 方式一: Judging by v-if, displaying different components
  • 方式二: The way of dynamic components
  • 方式三: use route router-link and router-view

v-if show different components

<template>
  <div>
    <button
      v-for="item in tabs"
      :key="item"
      @click="itemClick(item)"
      :class="{active: currentTab === item}"
    >{
    
    {
    
    item}}</button>

    <!-- 1.v-if的判断实现 -->
    <template v-if="currentTab === 'home'">
      <home></home>
    </template>
    <template v-else-if="currentTab === 'about'">
      <about></about>
    </template>
    <template v-else>
      <category></category>
    </template>

  </div>
</template>

<script>
import Home from './pages/Home.vue';
import About from './pages/About.vue';
import Category from './pages/Category.vue';

export default {
    
    
  components: {
    
    
    Home,
    About,
    Category
  },
  data () {
    
    
    return {
    
    
      tabs: ["home", "about", "category"],
      currentTab: "home"
    }
  },
  methods: {
    
    
    itemClick (item) {
    
    
      this.currentTab = item;
    }
  }
}
</script>

<style scoped>
.active {
    
    
  color: red;
}
</style>

Implementation of dynamic components

<template>
  <div>
    <button
      v-for="item in tabs"
      :key="item"
      @click="itemClick(item)"
      :class="{active: currentTab === item}"
    >{
    
    {
    
    item}}</button>
    <!-- 2.动态组件 -->
    <component :is="currentTab"></component>
  </div>
</template>

<script>
import Home from './pages/Home.vue';
import About from './pages/About.vue';
import Category from './pages/Category.vue';

export default {
    
    
  components: {
    
    
    Home,
    About,
    Category
  },
  data () {
    
    
    return {
    
    
      tabs: ["home", "about", "category"],
      currentTab: "home"
    }
  },
  methods: {
    
    
    itemClick (item) {
    
    
      this.currentTab = item;
    }
  }
}
</script>

<style scoped>
.active {
    
    
  color: red;
}
</style>

注意:上面is后的currentTab的值需要是什么内容呢?

  • Can be a component registered through the component function
  • Components registered in the components object of a component object

Pass-by-value for dynamic components

If it's dynamic components, can we pass values ​​to them and listen to events?

  • The value is the same as the basic component, but we need to 属性和监听事件put it on the component to use
    insert image description here

二、keep-alive

  • We transform the About component in the above case
  • Added a button to the function that can be incremented when clicked
    insert image description here
  • For example, if we set the counter to 10, can the state be maintained when switching to home and then switching back to about?
  • the answer is negative
  • This is because by default we are切换组件后,about组件会被销毁掉,再次回来时会重新创建组件
  • However, in some cases during development, we want to keep the state of the component instead of destroying it. At this time, we can use a built-in component: keep-alive
    insert image description here
    keep-alive property
  • include- string|RegExp|Array. Only components with matching names will be cached
    ;
  • exclude- string|RegExp|Array. Any component with a matching name will not
    be cached
  • max- number | string. The maximum number of component instances that can be cached. Once
    this number is reached, instances in the cached component that have not been accessed recently will be destroyed
  • include and exclude props allow components to conditionally cache
  • Both can be 逗号分隔字符串、正则表达式或一个数组used to represent
  • Matching first checks the component's own name 选项
    insert image description here
    cache component's lifecycle
For cached components, when entering again, we will not execute lifecycle functions such as created or mounted
  • But sometimes we do want to listen to when we re-enter the component and when we leave the component
  • At this time, we can use activated and deactivated these two life cycle hook functions to monitor
    insert image description here

3. Asynchronous components

  • Webpack code sub-package
  • Default packaging process
  • By default, in the process of building the entire component tree, because components and components are directly dependent on each other through modularization, webpack will package the component modules together (such as an app.js file) when packaging.
  • At this time 随着项目的不断庞大, app.js文件的内容过大, will cause首屏的渲染速度变慢
  • When packaging, the sub-package of the code
  • So, for some components that don't need to be used immediately, we can split them separately into some small code blocks chunk.js
  • These chunk.js will be loaded from the server when needed, and the code will be run to display the corresponding content
  • So how can the code be subpackaged in webpack?
    insert image description here
    Implementing asynchronous components in Vue
  • If our project is too large, for 某些组件what we want 通过异步的方式来进行加载(the purpose is to subcontract it), then Vue provides us with a function:defineAsyncComponent
  • defineAsyncComponent accepts two types of parameters
  • 类型一: Factory function, which needs to return a Promise object
  • 类型二: accepts an object type and configures the asynchronous function
  • 工厂函数类型的写法
    insert image description here- 对象类型一的写法
    insert image description here
    Async Components and Suspense
  • Suspense is a built-in global component that has two slots
  • default: If default can be displayed, then display the default content
  • fallback: If default cannot be displayed, the content of the fallback slot will be displayed
<template>
  <div>
    App组件
    <home></home>

    <suspense>
      <template #default>
        <async-category></async-category>
      </template>
      <template #fallback>
        <loading></loading>
      </template>
    </suspense>

  </div>
</template>

<script>
  import {
    
     defineAsyncComponent } from 'vue';

  import Home from './Home.vue';
  import Loading from './Loading.vue';

  // import AsyncCategory from './AsyncCategory.vue';
  const AsyncCategory = defineAsyncComponent(() => import("./AsyncCategory.vue"))

  // const AsyncCategory = defineAsyncComponent({
    
    
  //   loader: () => import("./AsyncCategory.vue"),
  //   loadingComponent: Loading,
  //   // errorComponent,
  //   // 在显示loadingComponent组件之前, 等待多长时间
  //   delay: 2000,
  //   /**
  //    * err: 错误信息,
  //    * retry: 函数, 调用retry尝试重新加载
  //    * attempts: 记录尝试的次数
  //    */
  //   onError: function(err, retry, attempts) {
    
    

  //   }
  // })

  export default {
    
    
    components: {
    
    
      Home,
      AsyncCategory,
      Loading
    }
  }
</script>

<style scoped>

</style>

Guess you like

Origin blog.csdn.net/qq_41880073/article/details/124026940
Recommended