动态组件——Vue开发中便捷的组件调用

195 阅读1分钟

什么事动态组件?

什么是动态组件?动态组件是指可以进行动态切换的组件机制,通过component钩子组件进行动态组件的动态调用。

动态组件有什么优势

动态组件可以实现在单页面内进行多个同质化组件的动态调用,在项目中,如果出现某个单独模块内进行多个组件的切换,可以使用动态组件进行加载,动态组件可以减少template的维护成本

我们可以用动态组件实现哪些功能?

在认识到动态组件的各种好处的同时,那么我们如何使用动态组件呢?

钩子函数渲染

首先在template部分进行component钩子函数的渲染

<template>
    <div class="pie-manage">
        <component :is="specialStateKey" :key="specialStateKey"></component>
    </div>
</template>

引入不同的组件

其次在script部分进行函数内容的封装

import Overview from "./overview.vue"; 
import StandBook from "./stand-book.vue";
import Folder from "./folder.vue"; 
export default {
    name: "farmland",
    data() {
        return {
            specialStateKey: "overview",
        };
    },
    components: {
        Folder,
        Overview,
        StandBook,
    },
    computed: {},
    mounted() {
        this.specialStateKey = "Folder";
        // this.specialStateKey = "Overview";
        // this.specialStateKey = "StandBook";
    },
    watch: {},
    methods: {},
};